c - String literals vs array of char when initializing a pointer -
inspired this question.
we can initialize char pointer string literal:
char *p = "ab"; and fine. 1 think equivalent following:
char *p = {'a', 'b', '\0'}; but apparently not case. , not because string literals stored in read-only memory, appears through string literal has type of char array, , initializer {...} has type of char array, 2 declarations handled differently, compiler giving warning:
warning: excess elements in scalar initializer
in second case. explanation of such behavior?
update:
moreover, in latter case pointer p have value of 0x61 (the value of first array element 'a') instead of memory location, such compiler, warned, taking first element of initializer , assigning p.
i think you're confused because char *p = "ab"; , char p[] = "ab"; have similar semantics, different meanings.
i believe latter case (char p[] = "ab";) best regarded short-hand notation char p[] = {'a', 'b', '\0'}; (initializes array size determined initializer). actually, in case, "ab" not used string literal.
however, former case (char *p = "ab";) different in initializes pointer p point first element of read-only string literal "ab".
i hope see difference. while char p[] = "ab"; representable initialization such described, char *p = "ab"; not, pointers are, well, not arrays, , initializing them array initializer entirely different (namely give them value of first element, 0x61 in case).
long story short, c compilers "replace" string literal char array initializer if suitable so, i.e. being used initialize char array.
Comments
Post a Comment