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

后端 未结 9 2062
暖寄归人
暖寄归人 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:09

    This answer is similar to the one given earlier in https://stackoverflow.com/a/1255185/1905491 but also takes the possible widths into account (as outlined by https://stackoverflow.com/a/6904396/1905491 which I did not recognize until my answer was rendered below it ;). The following snipped will print pointers as 8 0-passed hex characters on sane* machines where they can be represented by 32 bits, 16 on 64b and 4 on 16b systems.

    #include 
    #define PRIxPTR_WIDTH ((int)(sizeof(uintptr_t)*2))
    
    printf("0x%0*" PRIxPTR, PRIxPTR_WIDTH, (uintptr_t)pointer);
    

    Note the usage of the asterisk character to fetch the width by the next argument, which is in C99 (probably before?), but which is quite seldom seen "in the wild". This is way better than using the p conversion because the latter is implementation-defined.

    * The standard allows uintptr_t to be larger than the minimum, but I assume there is no implementation that does not use the minimum.

提交回复
热议问题