vendredi 29 mai 2015

String literals vs array of char when initializing a pointer

Inspired by this question.

We can initialize a char pointer by a string literal:

char *p = "ab";

And it is perfectly fine. One could think that it is equivalent to the following:

char *p = {'a', 'b', '\0'};

But apparently it is not the case. And not only because the string literals are stored in a read-only memory, but it appears that even through the string literal has a type of char array, and the initializer {...} has the type of char array, two declarations are handled differently, as the compiler is giving the warning:

warning: excess elements in scalar initializer

in the second case. What is the explanation of such a behavior?

Aucun commentaire:

Enregistrer un commentaire