Parsing a string for a pointer

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

those.

int main() { const char* address = "0x29cd10"; void* p; // I want p to point to address 0x29cd10 now... return 0; } 
+4
source share
3 answers

strtol allows you to determine the base (16, for hexadecimal or 0 for automatic detection based on the prefix 0x at the input) when parsing a string. After the pointer is stored as an integer, simply use reinterpret_cast to form the pointer.

+7
source
 sscanf(address, "%p", (void **)&p); 

There is no need for strtol or reinterpret_cast (which is C ++ anyway and is not suitable for C).

+3
source

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); 
0
source

Source: https://habr.com/ru/post/1333342/


All Articles