为什么通过使用printf(%x)来使指针的值不同? [英] Why the value of pointer is different by using printf(%x)?
问题描述
#include <stdio.h>
int main(void)
{
int *ptr;
printf("The Hex value of ptr is 0x%x",ptr);
printf("The pointer value of ptr is %p",ptr);
}
与输出有点不同,我不知道为什么
and the output is a little different that I don't know why
The Hex value of ptr is 0x24a77950
The pointer value of ptr is 0x7fff24a77950
它显示ptr的值是一个十六进制整数,但十六进制输出缺少部分7fff
.
It shows the value of ptr is a hex integer, but the hex output lack the part 7fff
.
这是printf格式问题还是其他原因?
Is this the printf formatting issue or something else?
推荐答案
%x将指针转换为无符号整数(32位长度).在64位计算机上,指针的长度为8字节(64位).
%x casts your pointer to an unsigned integer (32-bit length). On a 64-bit machine your pointer is of 8-byte (64 bit) length.
使用%p进行打印将以其完整大小-64位打印整个指针.但是,当您使用%x进行打印时,仅低32位被打印.因此,使用%p打印指针始终是安全的.
Printing with %p prints the whole pointer, in its complete size - 64 bits. But when you are printing with %x, only the lower 32 bits are printed. Hence it is always safe to print a pointer with %p.
您可以添加以下两行并进行验证:
You can do add extra 2 lines as below and verify:
printf("size of unsigned int is %lu\n", sizeof(unsigned int));
printf("size of pointer is %lu\n", sizeof(int *));
在具有64位操作系统的64位计算机上,这应该分别给您4和8.
On a 64-bit machine with a 64-bit operating system, this should give you 4 and 8 respectively.
查看已回答的两个类似问题:问题1 和<一个href ="https://stackoverflow.com/questions/399003/is-the-sizeofsome-pointer-always-equal-to-four">问题2
See two similar questions that have been answered: question 1 and question 2
这篇关于为什么通过使用printf(%x)来使指针的值不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!