简体   繁体   English

通过指针访问内部作用域中声明的变量是否安全?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM