Using char ** initializing char ** as array of strings in C

char *c[] = { "str1", "str2", "str3", "str4" }; 
char **c = { "str1", "str2", "str3", "str4" }; 

      

The first line is valid. The second is not. Why?

+3


source to share


2 answers


The second line is not an array, so you cannot use the array initialization syntax



+5


source


The first line is the standard syntax for initializing an array char*

.

The second line is just wrong, a type error.

Take a look at live on coliru: http://coliru.stacked-crooked.com/a/53464db7e2f31cfa

You can store it using a compound literal (C99):



char **c = (char*[]){ "str1", "str2", "str3", "str4" };

      

Remember that a volatile compound literal is in automatic storage if it is defined in a function.

If you want it to be a constant literal (and therefore in static storage) like strings (which vaguely have a type char[]

), do it like this:

char **c = (char**)&*(const char* const []){ "str1", "str2", "str3", "str4" };

      

+3


source







All Articles