问题
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.
#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;
}
回答1:
The scope of p ends at the closing bracket.
{
sequence p;
p.x = 11;
root.next = &p;
} <---- here
When you call printf("next %d\n",root.next->x); the variable p you are pointing to with root.next doesn't exist anymore. Therefore it isn't "safe", since it causes undefined behavior.
来源:https://stackoverflow.com/questions/28736448/is-it-safe-to-access-a-variable-declared-in-an-inner-scope-by-pointer