是否可以将内存地址保存为字符串?

时间:2012-04-10 15:41:48

标签: c++

说我有一个对象

MyObj stuff;

要获取内容的地址,我会打印

cout << &stuff << endl; 0x22ff68

我想在字符串中保存0x22ff68。我知道你不能这样做:

string cheeseburger = (string) &stuff;

有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:6)

您可以使用std::ostringstream。另请参阅this question

但是不要指望你必须具有真正意义的地址。使用相同的数据(因为address space layout randomization等),它可能会因同一个程序的一个运行而异。

答案 1 :(得分:3)

您可以尝试使用字符串格式

char strAddress [] =&#34; 0x00000000&#34 ;; //注意:您应该分配正确的大小,这里我假设您使用的是32位地址

sprintf(strAddress,&#34; 0x%x&#34;,&amp; stuff);

然后使用普通字符串构造函数

从此char数组创建字符串

答案 2 :(得分:1)

这是一种将指针的地址保存为字符串,然后将地址转换回指针的方法。我这样做是为了证明const并没有提供任何保护,但是我认为它很好地回答了这个问题。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    // create pointer to int on heap
    const int *x = new int(5);
        // *x = 3; - this fails because it's constant

    // save address as a string 
    // ======== this part directly answers your question =========
    ostringstream get_the_address; 
    get_the_address << x;
    string address =  get_the_address.str(); 

    // convert address to base 16
    int hex_address = stoi(address, 0, 16);

    // make a new pointer 
    int * new_pointer = (int *) hex_address;

    // can now change value of x 
    *new_pointer = 3;

    return 0;
}