Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what the differences between char** and char*[]

Tags:

c++

Recently, I need to declare a string array, so I wrote down the following statement:

const char** directories = {"cricket_batting", "cricket_bowling", "croquet", "tennis_forehand", "tennis_serve", "volleyball_smash"};

However, g++ showed me the error:

error: scalar object ‘directories’ requires one element in initializer

So I changed the statement to this:

const char* directories[] = {"cricket_batting", "cricket_bowling", "croquet", "tennis_forehand", "tennis_serve", "volleyball_smash"};

This time, it was right. But I can't exactly know the difference between char** and char[].

like image 737
alfredtofu Avatar asked Apr 03 '13 14:04

alfredtofu


2 Answers

= {...};

Initialisation of this form is known as list-initialization.

const char**

This type is a "pointer to pointer to const char".

const char*[]

This type is an "array of pointer to const char".

Simply put, you cannot initialise a pointer with list-initialization. You can initialise an array with list-initialization; it initializes each of the elements in the array with the items in the braced list.

The reason comes down to what exactly you get from a declaration. When you declare a const char**, all you get is a single pointer object. It's a const char**, which is a pointer promising to point at a pointer to const char. Nonetheless, all you actually have is the outer pointer. You can't then initialise this as though it's an array, since you only have one pointer. Where exactly are you going to store the elements of the initialization list? There is no array of pointers in which you can store them.

However, when you declare a const char*[], what you get is an array of pointers. The size of the array is determined by the size of the list because you have omitted it.

like image 173
Joseph Mansfield Avatar answered Sep 17 '22 22:09

Joseph Mansfield


The former is a pointer to a pointer to const char while the latter is an array to pointer to const char. The latter is the correct way to initialize an array of strings.
You would need to allocate memory using new to set up char** , for you can't simply initialize pointers with { }.

like image 26
bash.d Avatar answered Sep 19 '22 22:09

bash.d