Is it safe to access a variable declared in an inn

2019-05-11 10:18发布

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;
}

标签: c pointers scope
1条回答
Viruses.
2楼-- · 2019-05-11 10:52

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.

查看更多
登录 后发表回答