文字字符串放在哪里,为什么我可以返回指向它们的指针? [英] Where are literal strings placed and why can I return pointers to them?

查看:94
本文介绍了文字字符串放在哪里,为什么我可以返回指向它们的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 answer

令我惊讶的是,发现返回指向文字字符串的指针行得通,并且没有像我认为的那样出现段错误.我一直以为文字会被压入堆栈或放入其他临时存储器中,但限于功能范围之内.但是在这里,它们似乎比我想象的更静态.然后将它们放入整个可执行文件全局的某种字符串池吗?

I was surprised to discover that returning a pointer to the literal string worked, and didn't segfault like I thought it would. I always assumed that literals were pushed on to the stack or put in some other temporary memory, but where limited to the scope of the function. But here it seems that they are more static than I had imagined. Are they then put into something sort of string pool that's global to the entire executable?

如果我将字符串文字作为参数传递给函数,是否也一样?例如:

Also, is it the same thing if I pass a string literal as a parameter to a function? For example:

/* Where is the string literal in this example being placed? */
myfunc(value1, value2, "rainbowdash");

我希望有人能启发我.提前致谢! :)

I hope someone can enlighten me. Thanks in advance! :)

推荐答案

在C中,字符串文字具有静态存储持续时间.您的代码在逻辑上等效于:

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.

这篇关于文字字符串放在哪里,为什么我可以返回指向它们的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆