简体   繁体   English

打印变量地址

[英]Printing addresses of variables

When I run this code: 当我运行此代码时:

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;

I get this output: 我得到以下输出:

0x22fe30
0x22fe3f
0x22fe3f

At least in my estimation I should get the same number for all three of these statements. 至少在我的估计中,对于这三个语句,我应该得到相同的数字。 What is going on here? 这里发生了什么?

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

You are casting a pointer ( void* ) to a reference. 您正在将指针( void* )转换为引用。 This will not result in the same uint8_t , because it will make a reference to a temporary uint8_t , which you created out of a void pointer. 不会导致相同的uint8_t ,因为它将引用您从void指针创建的临时uint8_t And because a new uint8_t is created, you are getting different addresses. 并且由于创建了新的uint8_t ,因此您将获得不同的地址。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM