5

Suppose I have the memory address as a string representation (say "0x27cd10"). How can I convert this to a pointer (void*)?

i.e.

int main() {
     const char* address = "0x29cd10";
     void* p;

     // I want p to point to address 0x29cd10 now...

     return 0;
}
2
  • Do you know the address of some memory already before compile-time? Commented Dec 25, 2010 at 16:45
  • 1
    Out of curiosity, why would you want to do that? What's the scenario? Commented Dec 25, 2010 at 16:46

3 Answers 3

7

strtol lets you specify the base (16, for hexadecimal, or 0 to auto-detect based on the 0x prefix in the input) when parsing the string. Once you have the pointer stored as an integer, just use reinterpret_cast to form the pointer.

Sign up to request clarification or add additional context in comments.

2 Comments

Mine didn't convert from hex. Good catch
Example please?
4
sscanf(address, "%p", (void **)&p);

No need for strtol or reinterpret_cast (which is C++ anyway and no good in C only).

2 Comments

Well, (void **) is reinterpret_cast<> in this case.
@MaximEgorushkin p is void*, thus &p is void**, meaning the cast does nothing at all. You can use reinterpret_cast<> for an implicit_cast<>, but that's overkill.
0

You can also do it like this:

std::string adr = "0x7fff40602780";
unsigned long b = stoul(address, nullptr, 16);
int *ptr = reinterpret_cast<int*>(b);

If you want to convert a string address to an object pointer, here is another example:

std::string adr= "0x7fff40602780";
unsigned long b= stoul(adr, nullptr, 16);
unsigned long *ptr = reinterpret_cast<unsigned long*>(b);
Example *converted = reinterpret_cast<Example*>(ptr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.