Where is `%p` useful with printf?

Moeb picture Moeb · Mar 3, 2010 · Viewed 120.2k times · Source

After all, both these statements do the same thing...

int a = 10;
int *b = &a;
printf("%p\n",b);
printf("%08X\n",b);

For example (with different addresses):

0012FEE0
0012FEE0

It is trivial to format the pointer as desired with %x, so is there some good use of the %p option?

Answer

Peter Hosey picture Peter Hosey · Mar 3, 2010

They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer.

Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.

Always use %p for pointers.