c++ - 打印变量地址

标签 c++ pointers reference memory-address

当我运行这段代码时:

uint8_t stackVar = 0;
void* ptr = &stackVar;
uint8_t& ref = reinterpret_cast<uint8_t&>(ptr);
std::cout << (void*)&ref << std::endl;
std::cout << ptr << std::endl;
std::cout << (void*)&stackVar << std::endl;

我得到这个输出:

0x22fe30
0x22fe3f
0x22fe3f

至少在我看来,对于所有这三个陈述,我应该得到相同的数字。这是怎么回事?

最佳答案

uint8_t& ref = reinterpret_cast<uint8_t&>(ptr);

您正在将指针 ( void*) 转换为引用。这将不会产生相同的 uint8_t ,因为它会引用一个临时的 uint8_t ,它是您用 void 指针创建的。并且因为一个新的 uint8_t已创建,您将获得不同的地址。

也许你的意思是uint8_t& ref = reinterpret_cast<uint8_t&>(stackVar);

关于c++ - 打印变量地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229718/

相关文章:

c++ - 在 Makefile 中链接时定义变量的问题

c++ - Pig Latin 字符串迭代,多个单词

c - 指向 struct 的双指针中的第一个元素是 jiberrish

c++ - 使用指针写入 strcat() 时出错

c++ - 引用函数返回值

c++ - 引用对象的良好做法

c++ - 使用线程c++执行shell命令

c++ - 在 C++ 中获取工厂类的用户输入

c - C 中的箭头和点运算符

c++ - C++ 中的运算符重载 = operator