C++:取消引用十六进制值,有点语法问题

C++: dereference a hexadecimal value, kind of a syntax question

本文关键字:语法 问题 取消 引用 十六进制 C++      更新时间:2023-10-16

如何使第三个cout工作?我想提供一些确切的内存地址(我大胆地假设每次执行程序时它都会保持不变(,在这种情况下0x6ffdf0。

#include <iostream>
#include <string>
using namespace std;

int main(){
string colors = "blue";
string* pointer = &colors;
cout << pointer << endl;  //outputs 0x6ffdf0
cout << *pointer << endl; //outputs "blue"
cout << *0x6ffdf0;        //I want this to also output "blue"

return 0;
}

你不能让它安全地工作,这不是一个安全的假设。无法保证堆栈在您的进程中的位置,在进入main之前堆栈上将有多少,等等,并且实际上堆栈上的数量可能是用于启动程序的特定命令行的功能。

也就是说,出于学术目的,您正在寻找的语法来制定不安全的假设:

std::cout << *reinterpret_cast<const std::string *>(0x6ffdf0);

根据经验,如果你看到一个reinterpret_cast,总是会怀疑;这意味着"把这个位模式当作这个类型,结果是该死的"。

每次运行程序时,对象颜色的地址都可以不同。

如果你想将地址重新解释为整数值,那么你可以写一些类似的东西

#include <iostream>
#include <string>
#include <cstdint>
using namespace std;
int main(){
string colors = "blue";
string* pointer = &colors;
cout << pointer << endl;  // here can be any value 
// that can be changed from time to time
cout << *pointer << endl; //outputs "blue"
uintptr_t n = reinterpret_cast<uintptr_t>( pointer );
cout << *reinterpret_cast<string *>( n );
return 0;
}