简体   繁体   English

打印指针地址和&符地址之间的区别

[英]Difference between printing pointer address and ampersand address

int firstInt =10;
int *pointerFirstInt = &firstInt;


printf("The address of firstInt is: %u", &firstInt);
printf("\n");
printf("The address of firstInt is: %p", pointerFirstInt);
printf("\n");

The above code returns the following: 上面的代码返回以下内容:

The address of firstInt is: 1606416332
The address of firstInt is: 0x7fff5fbff7cc

I know that 0x7fff5fbff7cc is in hexadecimal, but when i attempt to convert that number to decimal it does not equal 1606416332 . 我知道0x7fff5fbff7cc是十六进制的,但是当我尝试将该数字转换为十进制时,它不等于1606416332 Why is this? 为什么是这样? Shouldn't both return the same memory address? 都不应该都返回相同的内存地址吗?

The reason for this is lies here: 原因在于:

C11: 7.21.6: C11:7.21.6:

If a conversion specification is invalid, the behavior is undefined . 如果转换规范无效, 则行为是undefined 288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. 288)如果任何参数不是对应转换规范的正确类型,则行为未定义。

From your hexadecimal address- 从您的十六进制地址-

The address of firstInt is: 0x7fff5fbff7cc

The size of the address is 6 bytes long. 地址的大小为6个字节长。 But Size of unsignedint is 4 bytes. 但是unsignedint大小为4个字节。 When you trying to print the address using %u , It will cause undefined behaviour. 当您尝试使用%u打印地址时,将导致未定义的行为。

So always print the address using %p . 因此,请始终使用%p打印地址。

it seems that you are working on an 64bit machine. 看来您在64位计算机上工作。 so your pointer is 64bit long 所以你的指针长64位

both ( &firstInt and pointerFirstInt ) are exactly same. 两者( &firstIntpointerFirstInt )完全相同。 but are displayed differently. 但显示方式不同。 "%p" knows that pointers are 64bit and displays them in hexadecimal. "%p"知道指针是64位的,并以十六进制显示它们。 "%u" shows decimal number and assumes 32bit. "%u"显示十进制数,并假定为32位。 so only a part is shown. 因此只显示了一部分。

if you convert 1606416332 to hexadecimal it looks like: 0x5FBFF7CC . 如果将1606416332转换为十六进制,则它看起来像: 0x5FBFF7CC you see that this is the lower half of the 64bit address. 您会看到这是64位地址的下半部分。

edit: further explanations: 编辑:进一步的解释:

since printf is a var-arg function all the parametes you give to it were put on the stack. 因为printf是一个var-arg函数,所以您赋予它的所有参数都放在堆栈中。 since you put 8 byte on it in both cases. 因为在这两种情况下,您都将8个字节放在上面。 since Pcs using little endian the lower bytes are put on it first. 由于Pcs使用Little Endian,因此将较低的字节放在首位。 the printf function parses the string and comes to an %[DatatypeSpecifier] point and reads as many bytes from stack as the datatype that is refered by DatatypeSpecifier requires. printf函数解析该字符串并到达%[DatatypeSpecifier]点,并从堆栈中读取与DatatypeSpecifier引用的数据类型一样多的字节。 so in case of "%u" it only reads 4 bytes and ignores the other bytes. 因此,对于"%u"它仅读取4个字节,而忽略其他字节。 Since you wrote "%u" and not "%x" it displays the value in decimal and not in hexadecimal form. 由于您写的是"%u"而不是"%x"因此它将以十进制而不是十六进制形式显示值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM