gpt4 book ai didi

c - 为什么 c 不替换 *b?

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:11 25 4
gpt4 key购买 nike

我有这个程序:

    int* b;
{
int a = 5;
b = &a;
} //a gets destroyed here
{
int c = 7; //c replaces a?
printf("c: %d\n", c);
}
printf("*b: %d", *b); //*b is still 5

为什么 c 不替换 *b 或类似的东西?是不是因为一些编译器优化(我用的是clang编译,但是我试过一些在线编译器,结果还是一样)

最佳答案

程序具有未定义的行为,因为指针 p 在该语句的范围内具有无效值

printf("*b: %d", *b);

并试图取消引用它。

指针有一个无效的(不确定的)值,因为它没有指向一个对象。指针早期指向的对象在此范围内不存在。

来自C标准(6.2.4对象的存储持续时间)

  1. ... If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

关于c - 为什么 c 不替换 *b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com