哪里是`%p`用printf的有用吗? [英] Where is `%p` useful with printf?
问题描述
毕竟,这两个语句做同样的事情...
After all, both these statements do the same thing...
int a = 10;
int *b = &a;
printf("%p\n",b);
printf("%08X\n",b);
例如(使用不同的地址):
For example (with different addresses):
0012FEE0
0012FEE0
这是小事与%X
所需的格式化指针,所以有一些很好的使用%的P
选项?
It is trivial to format the pointer as desired with %x
, so is there some good use of the %p
option?
推荐答案
他们不这样做同样的事情。后者 的printf
声明除$ p $点 b
为 unsigned int类型
,这是错误的,因为 b
是一个指针。
They do not do the same thing. The latter printf
statement interprets b
as an unsigned int
, which is wrong, as b
is a pointer.
指针和无符号整型
是不总是相同的尺寸,所以这些不能互换。当他们是不一样的尺寸(一个越来越普遍的情况下,64位CPU和操作系统变得越来越普遍),%X
只会地址的打印一半。在Mac上(也可能是其他一些系统),即将的破坏地址;输出将是错误的。
Pointers and unsigned int
s are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x
will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.
总是使用%P
为指针。
这篇关于哪里是`%p`用printf的有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!