C++/Pointers
Expert: Zlatko - 1/27/2010
QuestionHi Zlatko, I am trying to output ASCII chars from a to z but my function crashed. Pls advise me further. Tks.
Code:
#include <iostream>
#include <ctime>
#include <cstring>
#include <cstdlib>
using namespace std;
const int MAX = 10;
void outputChar (char*, int);
int main ()
{
char* a;
int size = MAX;
srand (time(NULL));
outputChar (a, 10);
}
//Output characters
void outputChar (char* a, int size)
{
for (int i = 0; i < size; i++)
{
*a = static_cast <char> (rand () % 26 + 97); //Displaying ASCII char for lower case a to z.
cout << &a [i] << "\t";
}
cout << endl;
}
AnswerHello Steve.
Your program is crashing because you are trying to put a byte into a location pointed at by 'a', but the 'a' pointer has not been initialized to point to a valid piece of memory.
In main, you need
char x[MAX];
char* a = x;
or
char a[MAX];
or
char* a = new char[MAX];
Any one of those will set aside MAX bytes in memory and set a to point to it.
In your for loop you want
a[i] = static_cast ....
not
*a = static_cast ....
because *a always refers to the start of the array
and you want
cout << a[i]
not
cout << &a[i]
because &a[i] gives the address of the i'th element.
OK?