- #36
Mark44
Mentor
- 37,757
- 10,120
In both cases the string literal "x" is in static storage. The pointer variable c holds the address of the string literal. The array variable c of the second example may or may not be on the stack, depending on whether the array is declared inside of or outside a function. I believe that the contents of the string literal get copied to the space allocated for the array. Also, the contents of the array don't get "deleted" when the array goes out of scope; the array contents merely get overwritten.Jarvis323 said:To be honest, the rules about C-strings aren't really that straightforward. I wasn't sure because I don't use C-strings whenever I don't have to. The article was the first entry in a google search for "return C-string". I was surprised a little that char * c = "x" (or const char *c = "x") is different than char c[] = "x". I guess the first one is a pointer to a string literal (which has static global storage for the lifetime of the program), and the second one is an array on the stack with automatic storage (gets deleted when out of scope).
Right, you aren't really "returning" a string literal -- just returning a pointer to where the literal is stored in memory.Jarvis323 said:You can return a string literal, with the return type const char *, in the sense you are returning a pointer to a const global static string literal that exists for the lifetime of the program. But you can't change a string literal.