[英]Is it safe to access a variable declared in an inner scope by pointer?
The program below prints 下面的程序打印
root 3
next 11
However, I am not sure if the program keeps root.next until the end of the program. 但是,我不确定程序是否保留root.next直到程序结束。
#include<stdio.h>
typedef struct sequence
{
int x;
sequence* next;
}sequence;
int main()
{
sequence root;
root.x = 3;
{
sequence p;
p.x = 11;
root.next = &p;
}
printf("root %d\n",root.x);
printf("next %d\n",root.next->x);
return 0;
}
The scope of p
ends at the closing bracket. p
的范围在结束括号处结束。
{
sequence p;
p.x = 11;
root.next = &p;
} <---- here
When you call printf("next %d\\n",root.next->x);
当你调用
printf("next %d\\n",root.next->x);
the variable p
you are pointing to with root.next
doesn't exist anymore. 你用
root.next
指向的变量p
不再存在。 Therefore it isn't "safe", since it causes undefined behavior. 因此它不是“安全的”,因为它会导致不确定的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.