为什么变量的地址与指针返回的地址不同?

问题描述

我正在使用这个操作函数获取指针地址,但它返回任何其他内容

#include<iostream>

using namespace std;

int *manipulate( int &b) {
    int *a=&b;
    cout<<&a<<" "<<&b<<" ";     // why memory add of 'a' and 'b' different ?
    return a;         // is it returing pointer which stores address of 'b' ?
}

int main() {
    int x=44;
    cout<<&x<<" "; // gives memory address of x;
    int *ptr=&x;
    cout<<ptr<<" "; //  gives mem address of x;
    int &l=x;
    cout<<&l<<" "; //  gives memory add of x;
    int *c=manipulate(x);  //storing returned pointer
    cout<<&c;  // why address of 'c' different to that of returned pointer?
    return 0;
}

解决方法

在操作函数中,您通过引用收到 &b

在这一行:

int *a=&b;

您已经定义了一个指针变量 a,其值为 b 地址

在这一行:

cout<<&a<<" "<<&b<<" ";

你已经打印了a(指针)的地址b的地址

如果你想要它们一样,你可以:

cout<<a<<" "<<&b<<" ";

最后你返回了 a(指向 b 的指针)

但在你的主要

int *c=manipulate(x);

您已经创建了一个指针名称 c,其地址值为 x

如果你想打印 x 的地址,你可以:

cout<<c;