C++:取消引用十六进制值,有点语法问题
C++: dereference a hexadecimal value, kind of a syntax question
如何使第三个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;
}
相关文章:
- C++:取消引用十六进制值,有点语法问题
- Qt的新信号/时隙语法问题 - 连接到一个简单的函数
- 语法问题:"char [5] const &"是什么意思?
- C++ std::函数语法问题
- C++.传递给函数.语法问题
- 内联访问说明符出现语法问题
- 无法在语法问题中返回简单函数
- Windows / Intel Compiler / Inline Assembler & GNU 语法问题
- 等级课程语法问题
- 可变模板的模板语法问题
- 使用自定义对象的地图使用MAP?可能是语法问题
- 语法问题
- GLSL语法问题:意外的new_identifier
- C++ 模板方法语法问题
- 从结构实例调用变量语法问题C++
- 一些C++语法问题
- 当一个规则使用BOOST_FUSION_ADAPT_STRUCT时,精神因果报应语法问题
- 在简单的哈希表中解决内存泄漏和语法问题
- 模板的语法问题
- C++ 标头语法问题