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"};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With