Difference between line% d and% p printf in c language?

I want a detailed explanation of the difference between using %d

and %p

for printing pointer


See also Why %p

returns a hexadecimal number? What are the cases when %d

and %p

return different values? Does the datatype only have how the user wants the output, or does it have something to do with memory locations?


source to share

3 answers

For a program to be clearly defined, the format specifier must match the type of the argument. Therefore you can use %p

but not %d

to print pointers. (The latter can happen with some architectures, but technically undefined behavior .)

The main reason why you cannot freely exchange %d

and %p

is that ints

pointers should not be the same size.

The format in which pointers are printed depends on the architecture (pointers can be of different sizes or indeed different structures ). However, it is common practice to rewrite memory addresses in hexadecimal, so this is usually the %p




These transformations are highly architecture dependent. One of the clearest differences is the actual 8086 mode, where int

is 16 bits and the pointer (large model) is 32 bits, but has a segment and an offset that is always written as segment: offset.

%d    takes 16 bits and displays it as a signed value  123
%p    takes a pointer and display it in address format    0fef:0004


Since it %p

was introduced relatively recently, I don't know of any implementations, but the PDP-11 library should implement it by showing a 16-bit address in octal format.



A variable pointer in C has a meaning in exactly the same way as other variable types like int, char, etc. The% p format string in the printf function simply indicates that the type of the "i" parameter is a pointer to printf instead of int. Thus, printf prints the Hex value of the i parameter because printf is represented by the i parameter as a pointer type. Regardless of the type of variable i, this value is 10 or 0xa. The difference between types i --- int or pointer ---- are different uses in C. If type i is treated as a pointer, you can visit the memory pointed to by the value of the i pointer or other operations, pointer types are supported. If the type of i is int, we can do some operations like addition or subtraction rather than visiting memory using the value of i.because the C grammar won't let you do that (just a warning). if you know what you want to do, you can do it.



All Articles