Which format specifier should I be using to print the address of a variable? I am confused between the below lot.
%u - unsigned integer
%x
Use %p
, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u
expects an unsigned int
, but what if void*
has a different size or alignment requirement than unsigned int
?)
*) [See Jonathan's fine answer!] Alternatively to %p
, you can use pointer-specific macros from
, added in C99.
All object pointers are implicitly convertible to void*
in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):
printf("x lives at %p.\n", (void*)&x);