It works, because pointers are in fact memory addresses, which in turn are represented by unsigned integer number (address).
Note, that long
is usually 4-byte long, so it will not be able to hold memory address, if you switch to 64-bit platform (where pointers are 64-bit / 8 byte long). In this case, converting pointer to int
/long
will truncate (and thus, invalidate) its content.
To store address value, use uintptr_t
(or signed version, intptr_t
), as described here:
intptr_t
, uintptr_t
Integer type capable of holding a value converted from a void pointer and then be converted back to that type with a value that compares equal to the original pointer.
Optional: These typedefs may not be defined in some library implementations.*
These types are optional, but available on most implementations. Even if they are not present, there should be platform-specific type defined for storing memory addresses.
Oh, and your point about conversions is not quite right - every integer (signed or unsigned) value can be converted to pointer (of any type, including void*
) via explicit conversion. It also works the other way around.