I know this is wrong:
char* getSomething() { char szLocal[5]; /* put something in the char array somehow */ return szLocal; }
...because szLocal can be destroyed sometime after the function returns.
But is this ok?
char* getSomethingElse() { return "something else"; }
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.
String literal as a Pointer String literals are stored just like arrays. The most important point to understand is that a string literal is a pointer to the first character of the array. In other words "Hello World" is a pointer to the character 'H' .
String literals are stored in C as an array of chars, terminted by a null byte. A null byte is a char having a value of exactly zero, noted as '\0'.
That is actually OK. The string literal is usually allocated in an immutable memory area that remains available for as long as your program is running.
See also the answers to when does c/c++ allocate string literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With