Search code examples
c++pointersmemoryfunction-pointersmemory-address

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


i am using this manipulate function to get the pointers address but it returns anything else.

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

Solution

  • in manipulate function you receive &b by reference.

    in this line:

    int *a=&b;
    

    you have defined a pointer variable a with value of b address

    in this line:

    cout<<&a<<" "<<&b<<" ";
    

    you have printed the address of a (the pointer) and address of b

    if you want them the same you could:

    cout<<a<<" "<<&b<<" ";
    

    and finally you have returned the a (pointer to b)

    but in your main

    int *c=manipulate(x);
    

    you have created a pointer name c with value of address of x

    if you want to print the address of x you could:

    cout<<c;