2

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.

Community
  • 1
  • 1
ace
  • 865
  • 2
  • 15
  • 24

3 Answers3

4

You create a variable called second, which gets assigned the value returned by 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:

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. 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:

int* sp = &second;
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
2

getSecond may return a reference to the second element of buff, but you then copy it into the variable second:

int second = getSecond();

So when you do &second, you get the address of second, not of the buff element.

You'll need to make second a reference too, to get the output you expect:

int& second = getSecond();
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

Is the function creating a temporary variable

No, you are creating one:

int second = getSecond();

should be

int &second = getSecond();