<分区>
Possible Duplicate:
Is returning a string literal address from a function safe and portable?
“life-time” of string literal in C
你好我有点困惑
char *func()
{
return "Hello";
}
这里的“Hello”是字符序列/数组。它是一个局部变量,它必须在函数返回后立即消失。那我们怎么能得到正确的值呢?
标签 c scope heap-memory local
<分区>
Possible Duplicate:
Is returning a string literal address from a function safe and portable?
“life-time” of string literal in C
你好我有点困惑
char *func()
{
return "Hello";
}
这里的“Hello”是字符序列/数组。它是一个局部变量,它必须在函数返回后立即消失。那我们怎么能得到正确的值呢?
最佳答案
"Hello"
是一个字符串文字,将在程序的生命周期内存在。引用C99标准的相关章节:
...The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence...
An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
函数的返回值应该是const char*
,因为尝试修改字符串文字是未定义的行为。
关于c - C 变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139002/