Ancient Dragon is correct, but I'd like to point out that there is a difference between
char *str = "Test";
/* and */
char str[] = "Test";
In both cases, "Test" is a string that resides in read-only memory. In the first case, str
is a pointer object that is initialized to the address of the read-only string, as Ancient Dragon described.
But in the second case, str
is an array object, and the initialization actually copies the string from read-only memory into the new (read-write) array. This memory has automatic storage duration, so it disappears when str
goes out of scope -- you don't have to worry about free()ing it like you do with malloc().
As an aside, this kind of automatic copying is possible only with initialization, not ordinary assignment, so the following is not valid:
char str[100];
str = "Test";
This is because an array name is not an lvalue. The other version,
char *str;
str = "Test";
is more or less fine, but you must be very careful if you ever modify the string because str points to read-only memory. If you don't try to modify the string, declare it as char const *str;
instead.