Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a pointer to a literal (or constant) character array (string)?

Tags:

c

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";   }   
like image 573
John Fitzpatrick Avatar asked Jan 29 '11 11:01

John Fitzpatrick


People also ask

Can you return a string literal?

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.

Is a string literal a pointer?

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' .

Where are string literals stored in C?

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'.


1 Answers

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.

like image 125
Roman Starkov Avatar answered Oct 02 '22 13:10

Roman Starkov