tags:

views:

1065

answers:

5

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

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

So, is there some good use of the %p option?

A: 

x is Unsigned hexadecimal integer ( 32 Bit )

p is Pointer address

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

Filip Ekberg
yeah, I already went through that page. What I wanted to know was why would you `use %p to print a pointer`. Anyways, Peter Hosey's answer answers my doubt.
Amoeba
+16  A: 

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.

Peter Hosey
%p will also use an adequate textural representation for pointer for the platform. On platforms where it is common to represent pointer in hex, this won't make a difference as long as the size is correct but for a segmented architecture (do you remember DOS?) it may use a segment:offset representation.
AProgrammer
One also needs to cast `b` to `void *` with the `%p` format - this is one of the few instances in C where one needs a cast.
Alok
+1  A: 

The size of the pointer may be something different than that of int. Also an implementation could produce better than simple hex value representation of the address when you use %p.

Tronic
A: 

x is used to print t pointer argument in hexadecimal.

A typical address when printed using %x would look like bfffc6e4 and the sane address printed using %p would be 0xbfffc6e4

codaddict
+3  A: 

At least on one system that is not very uncommon, they do not print the same:

~/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 a 0x prefix, for instance. Always use %p since it knows about the size of pointers, and how to best represent them as text.

unwind