简体   繁体   中英

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

It shows the value of ptr is a hex integer, but the hex output lack the part 7fff .

Is this the printf formatting issue or something else?

%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.

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 *));

On a 64-bit machine with a 64-bit operating system, this should give you 4 and 8 respectively.

See two similar questions that have been answered: question 1 and question 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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