问题描述
可能重复:结果
Is函数会返回一个字符串地址的安全和便携式?结果
“life-time”用C 字符串的
你好,我是有点困惑
char *func()
{
return "Hello";
}
下面你好是一个字符序列/数组。它是一个局部变量,它必须尽快消散作为函数返回。那为什么我们能够得到正确的值?
Here "Hello" is sequence/array of characters. It is a local variable and it must vanish away as soon as the function returns. Then how come we are able to get the correct value?
推荐答案
的你好
是一个字符串文字,将存在于程序的生命周期。引述C99标准的相关内容:
The "Hello"
is a string literal and will exist for the lifetime of the program. To quote the relevant sections of the C99 standard:
- 6.4.5字符串字面
...多字节字符序列,然后用于初始化数组的静态存储持续时间和长度刚好足以包含序列...
- 对象6.2.4贮存持续时间
其标识符被声明与外部或内部连接,或者与一个对象
存储类说明静态拥有的静态存储持续时间即可。其寿命是整个
方案及其存储值的执行被初始化仅仅一次,前程序
启动。
函数的返回值应为const char *
为试图修改字符串是未定义的行为。
The return value of the function should be const char*
as an attempt to modify a string literal is undefined behaviour.
这篇关于C变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!