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 - hexadecimal value
%p - void pointer
Which would be the optimum format to print an address?
This question is related to
c
pointers
format
memory-address
You can use %x
or %X
or %p
; all of them are correct.
%x
, the address is given as lowercase, for example: a3bfbc4
%X
, the address is given as uppercase, for example: A3BFBC4
Both of these are correct.
If you use %x
or %X
it's considering six positions for the address, and if you use %p
it's considering eight positions for the address. For example:
As an alternative to the other (very good) answers, you could cast to uintptr_t
or intptr_t
(from stdint.h
/inttypes.h
) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.
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 <inttypes.h>
, 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);
p
is the conversion specifier to print pointers. Use this.
int a = 42;
printf("%p\n", (void *) &a);
Remember that omitting the cast is undefined behavior and that printing with p
conversion specifier is done in an implementation-defined manner.
Source: Stackoverflow.com