Printf format specifier flags '0' for% p, correct or not?

Adds '0' as a flag to the printf % p format specifier correctly or not?

 #include <stdio.h> int main() { int a = 42; void* p = &a; printf("Pointer address: %08p", p); return 0; } 

Also on Ideone .

Compiling some code like the one above, I received no warning or nothing at all from Microsoft Visual C ++ 2015, but a warning from GCC 5.4.0:

": flag '0' used in the format '% p' ​​gnu_printf [-Wformat]"

Reading from cppreference printf , I see that:

0: for integers and floating point numbers, leading zeros are used to fill in the field instead of space characters. For integers, numbers are ignored if precision is explicitly specified. For other conversions using this flag, the behavior is undefined. this is ignored if a flag is present.

As far as I can interpret,% p is for the address of the pointer, which is an integer, after all, is this undefined behavior related to% p?
If not, then why the GCC -Wformat warning?

+5
source share
2 answers

%p for the address of the pointer, which is an integer after

Although pointers are numeric, the standard does not consider pointers to be an integral data type. Therefore, using the %08p format causes undefined behavior.

You can work around this problem by using the uintptr_t data uintptr_t by converting the pointer to it and then printing it as an unsigned integer:

 #include <cinttypes> #include <cstdint> int main() { int i = 123; void* p = &i; printf("%08" PRIxPTR "\n", (uintptr_t)p); return 0; } 

Demo version

+5
source

% p for the address of the pointer, which is an integer after all,

No, the pointer is not an integer from a system point such as C / C ++.

Pointers are neither arithmetic nor integer types to be pedantic, see std :: is_integral , std :: is_arithmetic .

+4
source

Source: https://habr.com/ru/post/1264625/


All Articles