Jan
Jan

Reputation: 2342

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"};

Upvotes: 3

Views: 146

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81926

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

Upvotes: 4

Related Questions