The type you're looking for is uintptr_t
, defined in <stdint.h>
. It is an unsigned integer type big enough to hold any pointer to data. The formats are in <inttypes.h>
. They allow you to format the code correctly. When you include <intttypes.h>
, it is not necessary to include <stdint.h>
too. I chose 16 assuming you have a 64-bit processor; you can use 8 if you're working with a 32-bit processor.
void printAddress(char *loc)
{
uintptr_t absLoc = (uintptr_t)loc;
uintptr_t minLoc = absLoc - (absLoc % 16);
uintptr_t maxLoc = minLoc + 16;
printf("0x%16" PRIXPTR " - 0x%16" PRIXPTR " - 0x%16" PRIXPTR "\n",
minLoc, absLoc, maxLoc);
}
You could also write:
uintptr_t minLoc = absLoc & ~(uintptr_t)0x0F;
See also Solve the memory alignment in C interview question that stumped me.
Note that there might, theoretically, be a system where uintptr_t
is not defined; I know of no system where it cannot actually be supported (but I don't know all systems).