首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++:取消引用十六进制值,这是一种语法问题

C++:取消引用十六进制值,这是一种语法问题
EN

Stack Overflow用户
提问于 2020-06-14 21:51:44
回答 2查看 235关注 0票数 0

我怎样才能让第三个笨蛋发挥作用?我想删除一些精确的内存地址(我大胆地假设每次执行程序时它都会保持不变),在本例中是0x6ffdf0。

代码语言:javascript
运行
复制
#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;
}
EN

回答 2

Stack Overflow用户

发布于 2020-06-14 22:01:02

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

尽管如此,出于学术目的,您希望实现不安全假设的语法是:

代码语言:javascript
运行
复制
std::cout << *reinterpret_cast<const std::string *>(0x6ffdf0);

根据经验,如果您看到一个reinterpret_cast,总是会产生怀疑;它的意思是‘把这个位模式当作是这种类型,结果就会被诅咒’。

票数 2
EN

Stack Overflow用户

发布于 2020-06-14 22:04:38

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

如果要将地址重新解释为整数值,则可以编写以下内容

代码语言:javascript
运行
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62378648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档