What's the proper use of printf to display pointers padded with 0s

后端 未结 9 2202
暖寄归人
暖寄归人 2021-01-31 14:32

In C, I\'d like to use printf to display pointers, and so that they line up properly, I\'d like to pad them with 0s.

My guess was that the proper way to do this was:

9条回答
  •  眼角桃花
    2021-01-31 15:35

    Maybe this will be interesting (from a 32-bit windows machine, using mingw):

    rjeq@RJEQXPD /u
    $ cat test.c
    #include 
    
    int main()
    {
        char c;
    
        printf("p: %016p\n", &c);
        printf("x: %016llx\n", (unsigned long long) (unsigned long) &c);
    
        return 0;
    }
    
    rjeq@RJEQXPD /u
    $ gcc -Wall -o test test.c
    test.c: In function `main':
    test.c:7: warning: `0' flag used with `%p' printf format
    
    rjeq@RJEQXPD /u
    $ ./test.exe
    p:         0022FF77
    x: 000000000022ff77
    

    As you can see, the %p version pads with zeros to the size of a pointer, and then spaces to the specified size, whereas using %x and casts (the casts and format specifier are highly unportable) uses only zeros.

提交回复
热议问题