0

I needed to convert the hexadecimal content of a pointer to a string. I already did that, using sprintf(). Now i need to do the opposite to get the pointer back. How would I go about this?

For example, I had this pointer: 0x55eb7e64b840. Then, i did this:

sprintf(str, "%p", p);

Now, str looks like this: "0x55eb7e64b840". From this string, can I get the pointer back?

Alcachofra
  • 135
  • 1
  • 1
  • 6
  • It's a pointer on what type ? Maybe https://stackoverflow.com/questions/10156409/convert-hex-string-char-to-int or https://stackoverflow.com/questions/3792610/convert-string-into-signed-int can help – Mickael B. May 03 '20 at 16:26
  • It's a pointer to a custom struct. Its size is 16 bytes. – Alcachofra May 03 '20 at 16:28
  • You can use `sscanf(str, "%p", &p)`. – Adrian Mole May 03 '20 at 16:28
  • In what context do you think you need to do this? If you are reloading data saved to a file, memory pointers are rarely useful. Offsets and type tags are usually required to restore data. – jwdonahue May 03 '20 at 16:35
  • I'm trying to send a struct from process CHILD to process PARENT via pipe(). I understand this might not work, I just wanted to test it out. How would you guys achieve that? In process CHILD, I create a struct, and do stuff with it. But now i need to send it to Process PARENT, the main process. – Alcachofra May 03 '20 at 16:39
  • Re "*I understand this might not work*", It won't work. On a computer with memory protection/virtualization (which includes basically everything other than microcontrollers), each process has its own address space, so a pointer in one process is useless in another. You'll need to serialize the data you wish the transmit, not the pointer. – ikegami May 03 '20 at 17:58

1 Answers1

0

Firstly, it is hardly a good idea to do this. (Causes all sorts of memory access violation problems)

Secondly, if you really want to, you can do:

sscanf(str,"%p",ptr);
user12986714
  • 741
  • 2
  • 8
  • 19