[英]C++: Why does my function return a reference address different from the dereferenced pointer's address?
I was under the impression that addresses of references to a dereferenced pointer were the same as the address of the pointer ( so question here ). 我的印象是,对解除引用的指针的引用地址与指针的地址相同( 所以问题在这里 )。
But when I write a function that returns a reference of a dereferenced pointer, I'm getting a different address from the original: 但是当我编写一个返回解除引用指针的引用的函数时,我得到的是与原始地址不同的地址:
#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);
}
The output I'm getting from that is: 我得到的输出是:
second:10 third?-16121856
second:10 third: 15
Buff 5 addr:0x8050b80 reffy: 0xbf7089b0
Is the function creating a temporary variable and returning its address or something? 该函数是否创建临时变量并返回其地址或其他内容? I can't quite figure out why it would be doing this. 我不清楚为什么会这样做。
You create a variable called second
, which gets assigned the value returned by getSecond()
. 您创建一个名为second
的变量,该变量将被赋予getSecond()
返回的值。 If I understand your question correctly, you perhaps meant to write: 如果我理解你的问题,你或许打算写:
int& second = getSecond();
// ^
// Mind the reference symbol
This way, second
would actually be a reference to the second element of buff
, rather than a separate variable with its own address, and the initialization: 这样, second
实际上是对buff
的第二个元素的引用,而不是具有自己的地址的单独变量,以及初始化:
int* sp = (int*)&second;
// ^^^^^^
// By the way, this is not necessary!
Would make sp
point to the second element of buff
(which seems to be what you expect) rather than to a separate variable called second
. 将sp
指向buff
的第二个元素(这似乎是你所期望的)而不是一个名为second
的单独变量。 As mentioned in the comments (thanks to DyP for noticing), the cast is superfluous (and you should not use C-style casts), so you should rewrite it just as: 正如评论中所提到的(感谢DyP注意到),演员阵容是多余的(你不应该使用C风格的演员表),所以你应该重写它:
int* sp = &second;
getSecond
may return a reference to the second element of buff
, but you then copy it into the variable second
: getSecond
可以返回对buff
的第二个元素的引用,但是然后将其复制到second
变量中:
int second = getSecond();
So when you do &second
, you get the address of second
, not of the buff
element. 所以当你做&second
,你得到的是second
地址,而不是buff
元素。
You'll need to make second
a reference too, to get the output you expect: 你也需要second
个参考,以获得你期望的输出:
int& second = getSecond();
Is the function creating a temporary variable 该函数是否创建临时变量
No, you are creating one: 不, 你正在创造一个:
int second = getSecond();
should be 应该
int &second = getSecond();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.