Difference between

Hello there,

While trying to solve an exercise, I stumbled upon a definition which I don't understand, What's an array of character pointers ?

When dynamically allocated I thought an array of character pointers was this:

char *p_to_ch = new char[5];

However a solution I found for the exercise declares/defines the array of character pointers as this:

char **ch_arr = new char* [SIZE];

I don't understand the usage of the 'star' operator on the right side. and therefore why does that force me to use the 'pointer to pointer' operator(**) on the left side.

Could anybody please explain this difference to me ?

Note. the array of character pointers will be used to hold strings.

Thanks in advance,
Best Regards,

Jose.
new char[5] dynamically allocates an array of 5 char objects and returns a char pointer (that is, of type char*) to the first object.

new char* [SIZE]; dynamically allocates an array of SIZE char pointer objects and returns a pointer to a char pointer (that is, of type char**) to the first (pointer) object.
Last edited on
Hi Athar,

I still don't get it.

Is the first one capable of holding strings ? or is just the second one capable ? and Why ?

does char pointer mean it can actually hold literal strings ?

Thank you !
Only the first is capable of holding a string (of max 4 (plus the null terminator) chars). The seond one consists of pointers to chars. A pointer is a variable that holds a mermory adress. So no string here though the pointer might point to a string then but that's another story.
Is the first one capable of holding strings ?

No. A char holds a single character, as the name indicates. That means you can store exactly five characters in that array. If you're talking about C strings, you can store up to 4, as one is necessary for the terminating \0.

or is just the second one capable ?

The second one can't exactly store strings, just char pointers. However, these pointers can point to the beginning of a char array that represents a string.

does char pointer mean it can actually hold literal strings ?

No. String literals are constant character arrays, so you need a pointer to const char if you want to point to a string literal.
Great ! that's a great explanation,

One final question, Why do I need the double star (**) on the left side of the 2nd declaration ?

I would only think that means it's a pointer to a pointer, but I'm not quite sure if that's the case, and more importantly, Why?

Thank you once more.

Jose.
An array is practically the same as a pointer. An array of a pointer is a pointer to a pointer.
char **ch_arr = new char* [SIZE];
Indicates that ch_arr can hold more than one array of characters. (more than one string) The right hand defines ch_arr to be an array of size SIZE that contains character pointers (strings).
Good !

Thank you all very much for the responses.

Have a nice day !
Topic archived. No new replies allowed.