Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is `%p` useful with printf?

Tags:

c++

c

printf

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?

like image 879
Moeb Avatar asked Mar 03 '10 07:03

Moeb


People also ask

What is the use of * p in C?

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.

What is P in printf?

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.

What is %p programming?

%p is a format specifier in C Programming language, that is used to work with pointers while writing a code in C.

What is %B in printf?

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).


2 Answers

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.

like image 193
Peter Hosey Avatar answered Oct 22 '22 00:10

Peter Hosey


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.

like image 26
unwind Avatar answered Oct 21 '22 23:10

unwind