You cannot modify string literals; doing so (as in your second case) is undefined behaviour.
char x[] = "foo";
creates a character array containing the characters f,o,o,\0
. It's basically a mutable copy of the string.
char *x = "foo";
creates a string pointer pointing to the "foo"
string literal. The literal may live in some read-only memory, in the program memory, or in a constant pool. Writing to it is undefined behaviour. Also, not that the type of a string literal is always const char[]
, so assigning it to a char *
is violating const-correctness.