我怎样才能让第三个笨蛋发挥作用?我想删除一些精确的内存地址(我大胆地假设每次执行程序时它都会保持不变),在本例中是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;
}发布于 2020-06-14 22:01:02
你不能让它安全工作,这不是一个安全的假设。无法保证堆栈在进程中的位置,在进入main之前堆栈上有多少,等等,实际上堆栈上的数量很可能是用于启动程序的特定命令行的函数。
尽管如此,出于学术目的,您希望实现不安全假设的语法是:
std::cout << *reinterpret_cast<const std::string *>(0x6ffdf0);根据经验,如果您看到一个reinterpret_cast,总是会产生怀疑;它的意思是‘把这个位模式当作是这种类型,结果就会被诅咒’。
发布于 2020-06-14 22:04:38
每次运行程序时,对象颜色的地址可能不同。
如果要将地址重新解释为整数值,则可以编写以下内容
#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;
}https://stackoverflow.com/questions/62378648
复制相似问题