Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why char initialization difference? C

Why are those two ways of initializing an array different from each other?

The first initialization gives me a compiler warning:

whereas the second one just works fine..

char *c_array_1[] = { {'a','b','c','d','e'}, {'f','g','h','i','j'} };

char *c_array_2[] = {"abcde","fghij"};
like image 839
Jan Avatar asked Feb 11 '26 19:02

Jan


1 Answers

So, in the C language, string literals (like: "abcde") automatically get storage allocated for them in the background of the compiler.

So, when you do

char *c_array_2[] = {"abcde","fghij"};

The compiler can, to some degree, change that to:

char *c_array_2[] = {Some_Pointer, Some_Other_Pointer};

However, for the other example:

char *c_array_1[] = { {'a','b','c','d','e'}, {'f','g','h','i','j'} };

The compiler will attempt to initialize. This will cause this line of code to be converted to the following (And probably push out a few warnings):

char *c_array_1[] = {'a', 'f'};

And then this is certainly not what you want ('a' is very likely not a valid pointer. You can see some more information on why the initialization happens like that from this question: Why is this valid C

like image 115
Bill Lynch Avatar answered Feb 13 '26 13:02

Bill Lynch