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

How to print value of a Variable using its memory address?

本文关键字:变量 打印 地址 何使用 内存      更新时间:2023-10-16

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

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

我试着跟随,但都是徒劳的

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

假设地址指向int,您可以:

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

作为文字0xfee2200是整数类型,而您期望的是指针。

你必须决定作为什么类型的数据你想要解释内存内容和转换它相应:

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