Where is `%p` useful with printf?

后端 未结 7 1535
鱼传尺愫
鱼传尺愫 2020-11-27 03:10

After all, both these statements do the same thing...

int a = 10;
int *b = &a;
printf(\"%p\\n\",b);
printf(\"%08X\\n\",b);

For example

7条回答
  •  醉梦人生
    2020-11-27 03:35

    They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer.

    Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.

    Always use %p for pointers.

提交回复
热议问题