Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between %d and %p printf format string directives in c language?

I want to get a detailed explanation on the difference between using %d and %p type for printing pointer.

Also Why does %p return hexadecimal? What are the cases when %d and %p return different values? Does datatype only represent the way the user wants the output or it has something to do with the memory locations too?

like image 837
Hari Avatar asked Dec 08 '22 06:12

Hari


1 Answers

For the program to be well-defined, the format specifier must match the type of the argument. Therefore you can use %p but not %d to print out pointers. (The latter might happen to work on some architectures but is technically undefined behaviour.)

The primary reason you can't freely interchange %d and %p is that ints and pointers don't have to have the same size.

The format in which pointers are printed out is architecture-specific (pointers can have different size or indeed different structure). It is, however, common to transcribe memory addresses in hexadecimal, so this is what %p usually does.

like image 157
NPE Avatar answered Dec 28 '22 10:12

NPE