【问题标题】:Is it safe to access a variable declared in an inner scope by pointer?通过指针访问在内部范围内声明的变量是否安全?
【发布时间】:2015-02-26 07:11:51
【问题描述】:

下面的程序打印

root 3                                                                                                                                                        
next 11

但是,我不确定程序是否会保留 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;
}

【问题讨论】:

    标签: c pointers scope


    【解决方案1】:

    p 的范围在右括号结束。

    {
        sequence p;
        p.x = 11;
        root.next = &p;
    } <---- here
    

    当您调用printf("next %d\n",root.next-&gt;x); 时,您使用root.next 指向的变量p 不再存在。因此它不是“安全的”,因为它会导致未定义的行为。

    【讨论】:

    • 那么是不是说“printf”打印正确的结果只是因为地址中的值没有被覆盖?
    • @ergoilto 查看生成的程序集。就 C 而言,它是未定义的。
    • “未定义的行为”可以表示任何事情,包括您希望的事情。永远不要指望它,下次它可能会引发一场热核战争
    • @ergoilto 非迂腐的答案是肯定的。
    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多