0

I'm trying to convert any variable to a void pointer and store the address as a number so I can later have access to the variable using the number as ID.

Here's my code:

#include <stdio.h>

int main()
{
    int num = 123456789;
    void *ptr = &num;
    unsigned long addr = *(unsigned long *)ptr;
    printf("addr: %lu\n", addr);
    ptr = (void *)addr;
    num = (int)ptr;
    printf("num: %d\n", num);
}

Result:

addr: 17275796522765372693
num: 123456789

Is this a correct and safe way to do it? Will it also work with non-primitive variable types like struct?

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • "Is this a correct and safe way to do it?" - No. `"cast from pointer to integer of different size"` Essentially it is pointer abuse. If you need to store an `int` for later retrieval, use an `int` for storage. – David C. Rankin Jul 06 '20 at 06:35
  • Use `uintptr_t` to store an address as a number instead of `unsigned long`. `#include `. But if it were me, I'd just pass around the `void*` as if it was a value. – selbie Jul 06 '20 at 06:35
  • 1
    Does this answer your question? [Converting double to void\* in C](https://stackoverflow.com/questions/6575340/converting-double-to-void-in-c) – gstukelj Jul 06 '20 at 06:35
  • @DavidC.Rankin The answer is no, of course, and it's a duplicate most likely, but it's technically not a duplicate of the linked question. The "*any variable*" here is not stored into a `void *ptr` but actually into the `unsigned long addr`, as confusing as the chosen names are. – dxiv Jul 06 '20 at 06:58
  • The commonality is the mismatch between pointer and integer size (and here the cast between the two `num = (int)ptr;`) I see what you are saying, but a further discussion here of mismatch wouldn't add to what the other answer already provides. – David C. Rankin Jul 06 '20 at 07:40

0 Answers0