关于解除引用和地址空间的基本C++指针问题

ja_*_*him 1 c++ variables pointers dereference address-space

在下面的代码中,基于阅读cplusplus.com,我试图测试我对指针的基本理解.

#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();
}
Run Code Online (Sandbox Code Playgroud)

这导致输出:

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
Run Code Online (Sandbox Code Playgroud)

哪个xx是在每个运行时更改的长数字.当我添加以下内容时:

    cout << "the address of foo is " << &foo << endl;
    cout << "the address of fubar is " << &fubar << endl;
Run Code Online (Sandbox Code Playgroud)

它导致:

the address of foo is xx
the address of fubar is xy
Run Code Online (Sandbox Code Playgroud)

运行时xy与哪里不同xx.

  • 问题1:在声明中,声明*bar是否在那个时刻使它成为一个"指针",直到它被使用,即它fubar = *bar在哪一点上是一个解除引用的变量?或者它是一个指针总是一个变量,这只是我得到所有nooby和绑定(可能是不正确的)语义?

  • 问题2:xx是一个改变每个运行时的长数字,所以我是对的,它是地址空间吗?

  • 问题3:我是否正确地认为虽然fubar并且foo具有相同的价值,但它们是完全独立的并且没有共同的地址空间?

Set*_*gie 6

  • 答案1:正确.变量bar是一个指针,使用*bar解引用指针并计算指针指向的内容.虽然它没有评估到[临时]副本,但是对它的目标的引用.

  • 答案2:"地址空间"与"地址"不同; 变量的地址只是它在内存中的位置,而程序的"地址空间"是它可以使用的所有内存.变量没有地址空间,程序可以.你们看到在你的程序的输出是地址(的地址foofubar).

  • 答案3:是的,你是对的.它们具有相同的值,但是一个会发生什么不会影响另一个(它们位于不同的地址,因此是不同的对象).