There is a difference between the char[]
and char*
variable declarations. As you noted in the comment in the code, char a[]
allocates the memory for a
on the stack and copyies the characters to that array, essentially making the declaration the same as:
char a[] = {'A', 'r', 'r', 'a', 'y', ' ', 'o', 'f', ..., '\0'};
When the function exits, the memory allocated on the stack for the array is gone, no longer making it safe to refer to via pointers.
When delcaring the variable via char* b
, the address of a statically allocated char array is stored in the memory for pointer b
. The actual memory where the string is allocated is not specified by the standard, but will be accessible throughout the execution of the code (in fact the compiler might reuse that memory if you declare another variable of char*
with the exact same string) -- so it is safe to pass that address around (e.g as a return value from a function).
As Rob pointed out, you should declare the type of the pointer const char*
to avoid accidentally trying to write to the memory where the string is stored: it is not guaranteed by the standard to have been placed in a writable segment of the memory. If you need to change it, you need to dynamically allocate the memory, copy the string into that allocated memory and return/work with that.