c - C 变量的范围

标签 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标准的相关章节:

  • 6.4.5 字符串文字

...The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence...

  • 6.2.4 对象的存储时长

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/

相关文章:

java - 如果要同步读,是否还需要同步写?

c - 使用 select() 在现有客户端或新客户端之间进行选择 (C)

c++ - 如何确定我在无线网络中连接的接入点的延迟和数据包丢失?

python - 从类定义中的列表推导式访问类变量

javascript - 如何使用 Cypress 将变量的存储值获取到 URL 命令中?

c++ - 当存在 std::vector 时,强指针导致应用程序关闭时堆损坏

c - 如何使用 Clang 的 AST?

C - 在不初始化的情况下在函数中传递局部变量

perl - 在 Perl 中本地更改类的属性

c++ - 包含链表的链表给出堆损坏错误 : Why?