Printf format specifiers for uint32_t and size_t

I have the following

size_t i = 0; uint32_t k = 0; printf("i [ %lu ] k [ %u ]\n", i, k); 

When compiling, I get the following warning:

 format '%lu' expects type 'long unsigned int', but argument has type 'uint32_t' 

When I ran this using splint, I got the following:

 Format argument 1 to printf (%u) expects unsigned int gets size_t: k 

Thanks so much for any advice,

+76
c printf
Jul 02 '10 at 18:37
source share
4 answers

It looks like you expect size_t be the same as an unsigned long (possibly 64 bits) when in fact it is unsigned int (32 bits). Try using %zu in both cases.

I'm not quite sure though.

+19
Jul 02 '10 at 18:40
source share

Try

 #include <inttypes.h> ... printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k); 

z represents an integer of length the same as size_t , and the PRIu32 macro defined in the C99 header inttypes.h represents an unsigned 32-bit integer.

+111
Jul 02 2018-10-18T00:
source share

All that is needed is that the format specifiers and types are consistent, and you can always do this to make it true. long is at least 32 bits, so %lu along with (unsigned long)k always correct:

 uint32_t k; printf("%lu\n", (unsigned long)k); 

size_t more complicated, so %zu was added in C99. If you cannot use this, then treat it the same as k ( long is the largest type in C89, size_t unlikely to be larger).

 size_t sz; printf("%zu\n", sz); /* C99 version */ printf("%lu\n", (unsigned long)sz); /* common C89 version */ 

If you do not specify format specifiers for the type you are passing, then printf will do the equivalent of reading too much or too little memory from the array. As long as you use explicit tricks to match types, they are portable.

+20
Nov 08 2018-11-11T00:
source share

If you do not want to use PRI * macros, another approach for printing an integer type ANY is to use for intmax_t or uintmax_t and use "%jd" or %ju , respectively. This is especially useful for POSIX types (or other operating systems) for which PRI * macros are not defined, for example off_t .

+16
Jul 03 '10 at 14:11
source share



All Articles