Cannot modify C string
Consider the following code.
int main(void) { char * test = "abcdefghijklmnopqrstuvwxyz"; test[5] = 'x'; printf("%sn", test); return EXIT_SUCCESS; }
In my opinion, this should print abcdexghij. However, it just terminates without printing anything.
int main(void) { char * test = "abcdefghijklmnopqrstuvwxyz"; printf("%sn", test); return EXIT_SUCCESS; }
This however, works just fine, so did I misunderstand the concept of manipulating C strings or something? In case it is important, I'm running Mac OS X 10.6 and it is a 32-bit binary I'm compiling.
The accepted answer is good, but not quite complete.
char * test = "abcdefghijklmnopqrstuvwxyz";
A string literal refers to an anonymous array object of type char[N]
with static storage duration (meaning it exists for the entire execution of the program), where N
is the length of the string plus one for the terminating '