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?
It's purpose is to print a pointer value in an implementation defined format. The corresponding argument must be a void * value. And %p is used to printing the address of a pointer the addresses are depending by our system bit.
Functions belonging to the printf function family have the type specifiers "%p" and "%x". "x" and "X" serve to output a hexadecimal number. "x" stands for lower case letters (abcdef) while "X" for capital letters (ABCDEF). "p" serves to output a pointer. It may differ depending upon the compiler and platform.
%p is a format specifier in C Programming language, that is used to work with pointers while writing a code in C.
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
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 int
s 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With