Search code examples
cpointersstring-parsing

How to make a pointer to a variable whose address is stored in a char array?


I have a program in which I have stored the address of the variable "var" in a char array by this:

int var = 10; //defined in somefile
sprintf(varAddress,"%p",&var)

So now varAddress stores the address of var (e.g. "0x7fff22b823dc").

Is there any way I can use varAddress to create a pointer to the variable var?


Solution

  • Assuming that the format of the string matches implementation-defined format supported by %p format conversion, you can parse the pointer as follows:

    int var = 10;
    // Writing the address into a string
    char buf[100];
    sprintf(buf, "%p", (void*)&var);
    printf("Address string: %s\n", buf);
    // Reading the address back
    void *ptr;
    sscanf(buf, "%p", &ptr);
    int *vptr = ptr;
    printf("Got address back: %p\n", (void*)vptr);
    

    Demo.

    Note that unless the value of the pointer came from this running process itself, any attempt at dereferencing this pointer would be undefined behavior. Moreover, the object whose pointer you retrieve from the string must still exist, and the type of the pointer must match the type of the object. All these constraints make it very hard to envision a use case in which reading a pointer from a string would serve any practical purpose.