0
#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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
mko
  • 21,334
  • 49
  • 130
  • 191
  • [using the wrong format specifier invokes *undefined behavior*](https://stackoverflow.com/a/30354164/995714) – phuclv Oct 28 '17 at 16:41
  • 1
    Possible duplicate of [What happens when I use the wrong format specifier?](https://stackoverflow.com/questions/16864552/what-happens-when-i-use-the-wrong-format-specifier) – phuclv Oct 28 '17 at 16:42

1 Answers1

5

%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

Community
  • 1
  • 1
codetwiddler
  • 452
  • 3
  • 10
  • 1
    wrong. `%x` doesn't cast any thing. [The behavior is undefined](https://stackoverflow.com/q/14504148/995714) – phuclv Oct 28 '17 at 16:40