Given the requirement that I need to store the value of a "generic" pointer in a struct and have no interest in the pointed-at memory itself, I find it more semantically correct to store it as an intptr_t
than a void*
. The question is whether a uintptr_t
is better suited or not, and when one is preferred over the other in general?
C – When to Prefer uintptr_t Over intptr_t
c++pointersvoid-pointers
Best Answer
It is mostly a stylistic argument (an optimizing compiler would probably generate the same, or very similar, code). However, pointer compares may be a tricky issue.
Remember than in purely standard C pointer compare is roughly meaningful only for pointers to the same aggregate data. You are probably not allowed to compare two results from
malloc
, e.g. to keep a sorted array of pointers.I would keep them as
void*
, or else asuintptr_t
. The signedintptr_t
has the inconvenience to seggregate negative and positive numbers, and where they are coming from significant application pointers, this is probably not welcome.Notice that a
void*
cannot be dereferenced: as anuintptr_t
, you have to cast it to do something useful with the data pointed by the address; howevervoid*
pointers can be passed to routines likememset
PS. I am assuming an ordinary processor (e.g. some x86, PowerPC, ARM, ...) with a flat virtual address space. You could find exotic processors -some DSPs perhaps- with very significant differences (and perhaps on which
intptr_t
is not always meaningful; remember that on the 1990s Cray Y-MP supercomputerssizeof(long*) != sizeof(char*)
; at that time C99 did not exist, and I am not sure its<stdint.h>
could be meaningful on such machines)