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

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

本文关键字:C++ 问题 指针 地址空间 于取消 取消 引用      更新时间:2023-10-16

在下面的代码中,基于阅读 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();
}

这导致输出:

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

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

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

它导致:

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

xy与运行时xx不同。

  • 问题1:在声明中,声明是否*bar使其成为当时的"指针",直到它被使用,即 fubar = *bar它在什么时候是取消引用的变量?还是指针始终是一个变量,而这只是我得到所有的nooby并被(可能不正确的(语义所束缚?

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

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

  • 答案 1:正确。变量 bar 是一个指针,使用 *bar 取消引用指针并计算指针指向的内容。要意识到,它不是评估为[临时]副本,而是对其目标的引用

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

  • 答案3:是的,你是对的。它们具有相同的值,但发生在一个上的事情不会影响另一个(它们位于不同的地址,因此是不同的对象(。

  1. 它被声明为类型 int* 它是用于存储地址的少量内存本身。指针变量始终是指针。使用取消引用运算符时,您将获得对存储的地址的变量的引用。
  2. 它是存储变量的虚拟内存中的实际地址。它们以十六进制显示(很可能(。它不是"地址空间"(见@Seth的答案(
  3. 是的。执行分配时,会将foo的值复制到fubar 中。但是,如果fubar是指针,并且您为其分配了bar,则它们的取消引用位置将是相同的。