简体   繁体   English

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

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

Here is the simple code:这是简单的代码:

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

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

The output is unexpected. output 出乎意料。 The first cout prints an address that looks like a address but the cout that is in the main prints a legit 0. I couldn't find an explanation anywhere.第一个 cout 打印一个看起来像地址的地址,但主要的 cout 打印一个合法的 0。我在任何地方都找不到解释。

Based on what I have experimented, I have concluded the following:根据我的实验,我得出以下结论:

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). 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). It does not do this in clang, but the value is undefined so both of these compilers are operating in accordance with the standard.它在 clang 中没有这样做,但该值未定义,因此这两个编译器都按照标准运行。

Try This Code.试试这个代码。
There was problem you were trying to access address of a local variable a it is not accessible out side of the function as_return().您试图访问局部变量的地址时出现问题,它在 function as_return() 之外无法访问。 So declare it in global so that it is accessible to everyone.因此,在全局中声明它,以便每个人都可以访问它。

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

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

. .
输出画面

I hope you got answer我希望你得到答案

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

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