问题描述
我想详细了解printing pointer
使用%d
和%p
类型之间的区别.
I want to get a detailed explanation on the difference between using %d
and %p
type for printing pointer
.
也为什么%p
返回十六进制?%d
和%p
返回不同值的情况是什么?数据类型仅表示用户想要输出的方式还是与存储位置有关?
AlsoWhy 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?
推荐答案
为使程序定义良好,格式说明符必须与参数的类型匹配.因此,您可以使用%p
而不是%d
来打印指针. (后者可能碰巧适用于某些体系结构,但从技术上讲不确定的行为.)
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.)
不能自由交换%d
和%p
的主要原因是ints
和指针不必具有相同的大小.
The primary reason you can't freely interchange %d
and %p
is that ints
and pointers don't have to have the same size.
打印指针的格式是特定于体系结构的(指针可以具有不同的大小,或者甚至可以具有不同的结构).但是,通常以十六进制形式记录内存地址,因此%p
通常这样做.
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.
这篇关于C语言中的%d和%p printf格式字符串指令之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!