【问题标题】:why address of variable is different to what is returned by pointer?为什么变量的地址与指针返回的地址不同?
【发布时间】:2021-04-01 21:55:09
【问题描述】:

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

#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;
}

【问题讨论】:

    标签: c++ pointers memory function-pointers memory-address


    【解决方案1】:

    在操作函数中,您通过引用收到&amp;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;
    

    【讨论】:

    • 如果 m answer 解决了您的问题,您可以使用“tick”接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2020-12-30
    相关资源
    最近更新 更多