0

I have an int* p1 and another string variable string addr containing the address which p1 points to (e.g: "0x555b236df005").

I have another pointer int* p2. How can I assign p2 to point to the address contained in addr (so that it points to the same location that p1 points to)?

This is a very simplified version of my problem, so doing p2 = p1 is not a solution for it.

Is there a way to do this? If so, how?

LeenA
  • 39
  • 5
  • 1
    Parse the string as an int then assign it with a cast. Can you also show complete code to go with your verbal explanation? See [mcve] for tips. – Code-Apprentice Aug 01 '19 at 17:27
  • Possible duplicate of [C++ convert hex string to signed integer](https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer) – Michael Chourdakis Aug 01 '19 at 17:29
  • Convert the string to an integer, cast the integer to a pointer. – john Aug 01 '19 at 17:35

1 Answers1

0

You can do what you want to do with std::stringstream and its helper function std::hex().

You have the hex value prepended with "0x" in your question details ... I was not sure if this would cause problems, but it seem not to.

#include <string>
#include <iostream>
#include <sstream>
#include <assert.h>

int main()
{
    int some_number = 42;
    int* ptr1 = &some_number;

    // convert a pointer to a string of hex digits
    std::stringstream ss1;
    ss1 << std::hex << ptr1;

    std::string ptr1_as_hex = ss1.str(); // Note ptr_as_hex will not be pre-prepended with "0x"
    ptr1_as_hex = "0x" + ptr1_as_hex;    

    // convert a string of hex digits to a pointer
    // by way of a long long
    long long ptr1_as_64bit_int;
    std::stringstream ss2(ptr1_as_hex);
    ss2 >> std::hex >> ptr1_as_64bit_int;
    int* ptr2 = reinterpret_cast<int*>(ptr1_as_64bit_int);

    assert(*ptr2 == 42);

    return 0;
}
jwezorek
  • 8,592
  • 1
  • 29
  • 46