它是安全的访问通过指针内部范围内声明的变量? [英] Is it safe to access a variable declared in an inner scope by pointer?

查看:114
本文介绍了它是安全的访问通过指针内部范围内声明的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面打印程序

 根3
接下来的11

不过,我不知道,如果该程序保持root.next,直到节目结束。

 #包括LT&;&stdio.h中GT;typedef结构序列
{
    INT X;
    序列*接下来的;
}序列;诠释的main()
{   序列根;
   root.x = 3;
   {
       序列p;
       p.x = 11;
       root.next =安培; P;
   }   的printf(根%d个\\ N,root.x);
   的printf(下一步%d个\\ N,root.next-> X);
   返回0;
}


解决方案

P 的范围在右括号结束。

  {
    序列p;
    p.x = 11;
    root.next =安培; P;
}< ----这里

当你调用的printf(下一步%d个\\ N,root.next-> X); 变量 P 您指向与 root.next 不存在了。因此,它不是安全的,因为它会导致不确定的行为。

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.

{
    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.

这篇关于它是安全的访问通过指针内部范围内声明的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆