![](/img/trans.png)
[英]Is the address of a reference to a dereferenced pointer the same as the address of the pointer?
[英]C++: Why does my function return a reference address different from the dereferenced pointer's address?
我的印象是,對解除引用的指針的引用地址與指針的地址相同( 所以問題在這里 )。
但是當我編寫一個返回解除引用指針的引用的函數時,我得到的是與原始地址不同的地址:
#include <iostream>
using namespace std;
int buff[10] = {0};
int& getSecond();
int main(){
buff[0] = 5;
buff[1] = 10;
buff[2] = 15;
int second = getSecond();
int* sp = (int*)&second;
cout << "second:" << *sp << " third?" << *(sp+1) << endl;
cout << "second:" << *(buff + 1) << " third: " << *(buff + 2) << endl;
cout << "Buff " << *buff << " addr:" << &(*buff) << " reffy: " << &second << endl;
}
int& getSecond(){
return *(buff + 1);
}
我得到的輸出是:
second:10 third?-16121856
second:10 third: 15
Buff 5 addr:0x8050b80 reffy: 0xbf7089b0
該函數是否創建臨時變量並返回其地址或其他內容? 我不清楚為什么會這樣做。
您創建一個名為second
的變量,該變量將被賦予getSecond()
返回的值。 如果我理解你的問題,你或許打算寫:
int& second = getSecond();
// ^
// Mind the reference symbol
這樣, second
實際上是對buff
的第二個元素的引用,而不是具有自己的地址的單獨變量,以及初始化:
int* sp = (int*)&second;
// ^^^^^^
// By the way, this is not necessary!
將sp
指向buff
的第二個元素(這似乎是你所期望的)而不是一個名為second
的單獨變量。 正如評論中所提到的(感謝DyP注意到),演員陣容是多余的(你不應該使用C風格的演員表),所以你應該重寫它:
int* sp = &second;
getSecond
可以返回對buff
的第二個元素的引用,但是然后將其復制到second
變量中:
int second = getSecond();
所以當你做&second
,你得到的是second
地址,而不是buff
元素。
你也需要second
個參考,以獲得你期望的輸出:
int& second = getSecond();
該函數是否創建臨時變量
不, 你正在創造一個:
int second = getSecond();
應該
int &second = getSecond();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.