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:
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.