Difference between

后端 未结 3 1615
囚心锁ツ
囚心锁ツ 2020-12-06 14:58

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

Also Why does

相关标签:
3条回答
  • 2020-12-06 15:22

    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.

    0 讨论(0)
  • 2020-12-06 15:32

    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.

    0 讨论(0)
  • 2020-12-06 15:40

    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.

    0 讨论(0)
提交回复
热议问题