June 23, 2010

How do you add a null pointer to a char array?

I have a char array that takes in words, char myarray[max_words][max_chars] and I want to add a null pointer (char *)0 to it. I am not sure how to do that. I have been getting compiling errors saying incompatible types.

You can't because you don't have an array of pointers. You have an array of characters which is max_words*max_chars big.

If you are trying to flag the end of the list, you could use an empty string. You create an empty string by putting a null character, aka ", in the first position(the null character is NOT the same things as NULL in C, although it is in C++):

myarray[x][0] = ";
Can also be written as:
myarray[x][0] = 0;
And in C++, but not C, as:
myarray[x][0] = NULL;

The other alternative is to make your array an array of pointers:
char *myarray[max_words];
Then you can write:
myarray[x] = NULL;

But then you will have to allocate memory for each new string in the array, and worry about freeing it later.

Filed under Pointer Puppies by Maria

Spread the Word!

Permalink Print Comment

Comments on How do you add a null pointer to a char array? »

June 23, 2010

Ratchetr @ 1:23 pm

You can't because you don't have an array of pointers. You have an array of characters which is max_words*max_chars big.

If you are trying to flag the end of the list, you could use an empty string. You create an empty string by putting a null character, aka '\0', in the first position(the null character is NOT the same things as NULL in C, although it is in C++):

myarray[x][0] = '\0';
Can also be written as:
myarray[x][0] = 0;
And in C++, but not C, as:
myarray[x][0] = NULL;

The other alternative is to make your array an array of pointers:
char *myarray[max_words];
Then you can write:
myarray[x] = NULL;

But then you will have to allocate memory for each new string in the array, and worry about freeing it later.
References :

Leave a Comment