如何使用其内存地址打印变量的值?

时间:2015-07-23 07:18:40

标签: c++ memory

假设0xfe2200是变量var2的内存地址,我想显示存储在其中的值,例如

cout<< "Value stored in the given address is :  " << 0xfe2200 << "    ";

我试过跟随,但一切都是徒劳的

cout << "Value is :  " << *0xfee2200 << " ;
cout << "Value is :  " << &0xfee200 << "  ; 

2 个答案:

答案 0 :(得分:4)

假设地址指向int,您可以执行以下操作:

cout << "Value is :  " << *reinterpret_cast<int*>(0xfee2200);

因为文字0xfee2200是一个整数类型,而你期望一个指针。

答案 1 :(得分:2)

您必须决定要解释内存内容的数据类型,并相应地强制转换

const char* tmp = "foofoo"; // Valid ptr for this example
const void* address = tmp; // Set to your address

const int* i = reinterpret_cast<const int*>(address);
const unsigned short* us = reinterpret_cast<const unsigned short*>(address);
const char* c = reinterpret_cast<const char*>(address);

std::cout << "i: " << (*i)
          << "\nus: " << (*us)
          << "\nc: " << (*c);

输出:

  

我:1718579046
  我们:28518
  c:f