14

Say I have an object

MyObj stuff;

To get the address of stuff, I would print

cout << &stuff << endl; 0x22ff68

I want to save 0x22ff68 in a string. I know you can't do this:

string cheeseburger = (string) &stuff;

Is there a way to accomplish this?

3 Answers3

11

Here's a way to save the address of a pointer to a string and then convert the address back to a pointer. I did this as a proof of concept that const didn't really offer any protection, but I think it answers this question well.

#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;
}
Eric Wiener
  • 4,929
  • 4
  • 31
  • 40
10

You could use std::ostringstream. See also this question.

But don't expect the address you have to be really meaningful. It could vary from one run to the next of the same program with the same data (because of address space layout randomization, etc.)

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    I understand that. It only needs to be correct for current run. Thank you! –  Apr 10 '12 at 15:51
5

You can try using a string format

char strAddress[] = "0x00000000"; // Note: You should allocate the correct size, here I assumed that you are using 32 bits address

sprintf(strAddress, "0x%x", &stuff);

Then you create your string from this char array using the normal string constructors

J_D
  • 3,526
  • 20
  • 31