繁体   English   中英

返回的地址始终为 0 而不是实际值

[英]The address always returned is 0 instead of the actual value

这是简单的代码:

int *ad_return()
{
    int a=600;
    cout << &a << endl;
    return &a;
}

int main()
{
    cout << ad_return();
    return 0;
}

output 出乎意料。 第一个 cout 打印一个看起来像地址的地址,但主要的 cout 打印一个合法的 0。我在任何地方都找不到解释。

根据我的实验,我得出以下结论:

Since the address of a local variable that has already went out of scope is undefined, it seems that gcc and g++ decided to implement a feature that sets this to zero (probably to make sure that the code segfaults instead of generating thoroughly bizarre behaviour). 它在 clang 中没有这样做,但该值未定义,因此这两个编译器都按照标准运行。

试试这个代码。
您试图访问局部变量的地址时出现问题,它在 function as_return() 之外无法访问。 因此,在全局中声明它,以便每个人都可以访问它。

   #include<iostream>
  using namespace std;
  int a;
  int *ad_return()
  {
   a=600;
   cout << &a << endl;
   return &a;
  }

  int main()
  {
   cout << ad_return();
   return 0;
   }

.
输出画面

我希望你得到答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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