簡體   English   中英

為什么變量的地址與指針返回的地址不同?

[英]why address of variable is different to what is returned by pointer?

我正在使用這個操作 function 來獲取指針地址,但它返回任何其他內容。

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

在操作 function 時,您會通過引用收到&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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM