【问题标题】:returning the address of a pointer返回指针的地址
【发布时间】:2015-12-02 05:36:46
【问题描述】:

我正在尝试使用以下代码返回指针的地址:

#include <iostream>
using namespace std;

int main(){
    int x = 5;
    int *p = &x;
    //int **pp = &p;
    cout << &p << endl;
    return 0;
}

但是,打印出来的是 0x28fea8,它与 x 本身的地址相同。现在,如果我取消注释上面唯一的注释行并保留其他所有内容,那么打印出来的是 0x28fea4,这似乎是指针的正确地址。

我的问题是为什么我需要未注释的行来显示指针的正确地址?

如果留下注释,为什么“cout

不管另一行如何,“cout

如果有帮助,我将使用 Qt Creator 作为我的编译器/IDE。我从以下链接下载了我的编译器:http://web.stanford.edu/~rawatson/qt/windows_install/index.html

编辑:好吧,我真傻。我的问题是我通过更改值来比较地址,然后重新运行程序。相反,我应该通过在一个程序运行中打印它们来进行比较。当我在一个程序中进行比较时,我会得到 p 和 &p 的不同地址,这是应该的。

【问题讨论】:

  • 您可以将使用过的编译器标志添加到您的帖子中吗?您的示例在带有 -O3 的 Ubuntu 上的 G++ 4.8.4 上运行良好:当我打印 p 和打印 &p 时,我得到两个不同的输出。
  • However what gets printed ... is the same address as x itself. False. p&amp;x 是一样的。 &amp;p 是不同的,正如自然所期望的那样。
  • 也许是我的编译器,我更新了我的帖子,并附上了我下载它的链接。
  • 你显示的程序只打印一个值,而不是两个,所以不清楚你在比较什么。显示您正在运行的确切代码,以及程序产生的输出,其中包括这两个值。
  • 你刚刚发现我的问题是我比较了不同程序运行的地址。

标签: c++ pointers


【解决方案1】:

我无法使用this 代码重现您所说的内容:

#include <cstdio>
using namespace std;

int main() {
    int x = 5;
    int* p = &x;

    printf("x address: %p\n", &x);
    printf("p value: %p\n", p);
    printf("p address: %p\n", &p);

    return 0;
}

我得到以下输出:

x address: 0xbfd6bba8
p value: 0xbfd6bba8
p address: 0xbfd6bbac

这是正确的,实际上&amp;p&amp;x+4,这在 32 位架构上是正确的,因为它们是在堆栈上分配的。

【讨论】:

  • 是的,我的问题在于我比较了来自不同程序运行的地址。为了得到正确的比较,我应该像你一样在一个运行的程序中打印地址。
【解决方案2】:
int x = 5;
int *p = &x; // b stores addres of variabile a

cout << "Adress of x is : " << p <<endl; // printing the  adress of a
cout << "Value of x is : " << *p << endl; // printing the variabile stores in a 

int **pp = &p; // pp stores thea adress of p
cout <<"Adress of p is" << pp << endl; //printing the adress of p
cout << "Adress of x is" <<*pp << endl; //printing the adress of x
return 0;

希望cmets能解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2021-04-01
    • 2013-10-04
    相关资源
    最近更新 更多