4

I have some trouble with a book that I am currently reading about C and assembly. The author uses a 32 bit environment while I am using 64-bit. The problem is that the author often uses

printf("%08x", &var);

To print addresses which works fine on 32 bit. But when I run this on 64-bit I get only half of the address while %p gives me the whole address... So why is this so? I of course use %016xinstead of %08x.

The author only uses %p for pointers. So when should I use what?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
crush3dice
  • 198
  • 1
  • 2
  • 15
  • 4
    `%p` should be right one in both cases; and `&var` is a pointer. – ShinTakezou Jan 04 '14 at 14:44
  • It's not clear if they often use "%8x" or "%p" anyway the right one for pointers is **always** "%p". – Adriano Repetti Jan 04 '14 at 14:45
  • what I like to do when dealing with printing a lot of pointers is: `printf("0x%" PRIxPTR", (uintptr_t)(&var))` you get `PRIxPTR` and `uintptr_t` from `inttypes.h` I like this approach, because the semantics of printing an integer is pretty clear to me, while the semantics of printing a pointer is kind of foggy. Also, `uintptr_t` is guaranteed to be able to hold the integer representation of a pointer, so it's portable and semantically correct - everyone wins :) – Andreas Grapentin Jan 04 '14 at 15:48

1 Answers1

7

To print pointers in printf, using %p with void * type is the way according to the C standard.

printf("%p", (void *)&var);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294