Where are literal strings placed and why can I return pointers to them?

前端 未结 3 1020
有刺的猬
有刺的猬 2021-01-23 22:26

I stumbled upon this function in an answer to this question:

/* Note: I\'ve formatted the code for readability. */
const char * getString() {
    const char *x =         


        
3条回答
  •  有刺的猬
    2021-01-23 22:31

    In C, string literals have static storage duration. Your code is logically equivalent to:

    const char * getString() {
        static const char literal[] = "abcstring";
        const char *x = literal;
        return x;
    }
    

    with the exception that in the version with the string literal, the storage for the string could overlap with the storage of other string literals.

提交回复
热议问题