Reputation: 279
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;
}
Upvotes: 5
Views: 5573
Reputation: 33
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);
Upvotes: 0
Reputation: 580
sscanf(address, "%p", (void **)&p);
No need for strtol or reinterpret_cast (which is C++ anyway and no good in C only).
Upvotes: 4
Reputation: 283713
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.
Upvotes: 7