加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

变量的范围.内部工作基础

发布时间:2020-12-16 10:23:12 所属栏目:百科 来源:网络整理
导读:这是关于变量假设范围的一个非常基本的问题.我有一个fiollowing代码: int main(){ int *p; p=func(); printf("%d",*p); return 0;}int *func(){ int i; i=5; return i;} 我的问题 i的范围在func()中完成,但是,因为我将返回i的地址,我将能够在main()中访问和
这是关于变量假设范围的一个非常基本的问题.我有一个fiollowing代码:

int main()
{
    int *p;
    p=func();
    printf("%d",*p);
    return 0;
}

int *func()
{
   int i;
   i=5;
   return &i;
}

我的问题

> i的范围在func()中完成,但是,因为我将返回i的地址,我将能够在main()中访问和print5吗?
>如果没有,为什么?编译器是否在该地址空间中放置了一个垃圾值(我不认为这样做了).
>变量范围究竟意味着什么?分配给i的内存是否在其范围结束时被释放?

解决方法

变量的范围是可以访问它的区域.
变量的生命周期是保证变量存在的时间.

在你的情况下,我的生命在不超出它的功能范围内.这意味着我不能保证在功能之外存在.它不是必需的,并且它是未定义的行为来访问函数之外的局部变量.

The scope of i is finished in func() but,since I am returning the address of i will I be able to access and print 5 in main()?

你可能会,但它是未定义的行为.所以不要这样做.

If not,why? does the compiler puts a garbage value in that address space (I don’t think this is done)

编译器可以将它选择的任何内容放在该位置,一旦函数返回,地址位置就会保存一个Indeterminate值.

What actually it means by the scope of a variable is ended ? Also does the memory allocated to i is freed when its scope ends?

i是一个自动/局部变量,一旦声明它们的作用域{,}结束,所有自动变量都会被释放.因此名称自动.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读