当我运行这段代码时:
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/