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;
}
The scope of
p
ends at the closing bracket.When you call
printf("next %d\n",root.next->x);
the variablep
you are pointing to withroot.next
doesn't exist anymore. Therefore it isn't "safe", since it causes undefined behavior.