Where is `%p` useful with printf?

后端 未结 7 1566
鱼传尺愫
鱼传尺愫 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:33

    At least on one system that is not very uncommon, they do not print the same:

    ~/src> uname -m
    i686
    ~/src> gcc -v
    Using built-in specs.
    Target: i686-pc-linux-gnu
    [some output snipped]
    gcc version 4.1.2 (Gentoo 4.1.2)
    ~/src> gcc -o printfptr printfptr.c
    ~/src> ./printfptr
    0xbf8ce99c
    bf8ce99c
    

    Notice how the pointer version adds a 0x prefix, for instance. Always use %p since it knows about the size of pointers, and how to best represent them as text.

提交回复
热议问题