Reputation: 121
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?
Upvotes: 4
Views: 8913
Reputation: 504
A pointer of variable in C has value just like other type of variable such as the int、char and so on. The %p format string in the printf function just indicates that the type of parameter "i" is pointer to the printf instead of int. Thus printf outputs the Hex value of parameter i because printf seem the parameter i as a pointer type. No matter what the type of variable i is, the value is same----10 or 0xa. The difference between the types of i---int or pointer ----is the different ways to use in C. if type of i is regarded as pointer, you can visit the memory specified by value of pointer i or other operations the pointer type supports. If type of i is int, we can do some operations such as addition or subtraction rather than visiting the memory by using value of i, because the grammar of C do't allow you to do that(just warning). if you know what you want to do, you can do that.
Upvotes: 0
Reputation: 500177
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.
Upvotes: 13
Reputation: 57774
Those conversions are highly architecture dependent. One of the most clear distinctions are with the real mode 8086 where int
is 16 bits and a (large model) pointer is 32 bits but has a segment and offset which are 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 %p
was introduced relatively recently I don't know of any implementations but a PDP-11 library ought to implement it by display the 16-bit address in octal.
Upvotes: 1