Is it safe to access a variable declared in an inner scope by pointer?

时光毁灭记忆、已成空白 提交于 2019-12-10 09:44:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!