Where is `% p` useful to use printf?

In the end, both of these statements do the same ...

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 , is it good to use the %p parameter?

+44
c ++ c printf
Mar 03 '10 at 7:55
source share
7 answers

They do not do the same. The last printf statement interprets b as unsigned int , which is not true since b is a pointer.

Pointers and unsigned int not always the same size, so they are not interchangeable. When they do not have the same size (an increasingly common case when 64-bit processors and operating systems become more common), %x will only print half the address. On a Mac (and possibly some other systems) this will destroy the address; the output will be wrong.

Always use %p for pointers.

+107
Mar 03 '10 at 8:04
source share
β€” -

In at least one system, which is not very unusual, they do not print the same thing:

 ~/src> uname -m i686 ~/src> gcc -v Using built-in specs. Target: i686-pc-linux-gnu [some output snipped] gcc version 4.1.2 (Gentoo 4.1.2) ~/src> gcc -o printfptr printfptr.c ~/src> ./printfptr 0xbf8ce99c bf8ce99c 

Notice how the pointer version adds the 0x prefix, for example. Always use% p as it knows about the size of the pointers and how best to represent them as text.

+6
03 Mar. 2018-10-03T00:
source share

You cannot depend on %p displaying the 0x prefix. In Visual C ++, this is not the case. Use %#p to carry.

+5
Jun 06 '12 at 6:21
source share

The size of the pointer may differ from the size of the int . Also, using %p for implementation may be better than a simple hexadecimal representation of the address.

+4
Mar 03 '10 at 8:05
source share

x Unsigned hexadecimal integer (32 bits)

p - pointer address

See printf in the C ++ Reference . Even if both of them write the same thing, I would use %p to print the pointer.

+2
Mar 03 '10 at 8:00
source share

When you need to debug, using the printf parameter with %p really useful. You see 0x0 when you have a NULL value.

0
May 23 '16 at 16:36
source share

x used to print the argument t of the pointer in hexadecimal format.

A typical address when printed using %x will look like bfffc6e4 , and the default address %p will be 0xbfffc6e4

-one
Mar 03 '10 at 8:05
source share



All Articles