关于取消引用和地址空间的基本C++指针问题
Basic C++ pointer questions on dereferencing and 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();
}
这导致输出:
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并被(可能不正确的(语义所束缚?问题 2:
xx
是一个改变每个运行时的长数字,所以我说它是地址空间是对的吗?问题3:我是否正确地认为,虽然
fubar
和foo
具有相同的价值,但它们是完全独立的,没有共同的地址空间?
-
答案 1:正确。变量
bar
是一个指针,使用*bar
取消引用指针并计算指针指向的内容。要意识到,它不是评估为[临时]副本,而是对其目标的引用。
答案2:"地址空间"不同于"地址"> ;变量的地址只是它在内存中的位置,而程序的"地址空间"是它可以使用的所有内存。变量没有地址空间,程序有。您在程序输出中看到的是地址(
foo
和fubar
的地址(。答案3:是的,你是对的。它们具有相同的值,但发生在一个上的事情不会影响另一个(它们位于不同的地址,因此是不同的对象(。
- 它被声明为类型
int*
它是用于存储地址的少量内存本身。指针变量始终是指针。使用取消引用运算符时,您将获得对存储的地址的变量的引用。 - 它是存储变量的虚拟内存中的实际地址。它们以十六进制显示(很可能(。它不是"地址空间"(见@Seth的答案(
- 是的。执行分配时,会将
foo
的值复制到fubar
中。但是,如果fubar
是指针,并且您为其分配了bar
,则它们的取消引用位置将是相同的。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题