c++variablespointersdereferenceaddress-space

Basic C++ pointer questions on dereferencing and address-space


In the following code, based on reading cplusplus.com, I'm trying to test my basic understanding on pointers.

#include <iostream>
using namespace std;

int main() {
    int foo, *bar, fubar;
    foo = 81;
    bar = &foo;
    fubar = *bar;
    cout << "the value of foo is " << foo << endl;
    cout << "the value of &foo is " << &foo << endl;
    cout << "the value of bar is " << bar << endl;
    cout << "the value of *bar is " << *bar << endl;
    cout << "the value of fubar is " << fubar << endl;
    cin.get();
}

That leads to the output:

the value of foo is 81
the value of &foo is xx
the value of bar is xx
the value of *bar is 81
the value of fubar is 81

Where xx is some long number that changes at each runtime. When I add the following:

    cout << "the address of foo is " << &foo << endl;
    cout << "the address of fubar is " << &fubar << endl;

It leads to:

the address of foo is xx
the address of fubar is xy

Where xy is different to xx on runtime.


Solution