C语言 uint32_t 和 size_t 的 printf 格式说明符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3168275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printf format specifiers for uint32_t and size_t
提问by ant2009
I have the following
我有以下
size_t i = 0;
uint32_t k = 0;
printf("i [ %lu ] k [ %u ]\n", i, k);
I get the following warning when compiling:
编译时我收到以下警告:
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
Many thanks for any advice,
非常感谢您的任何建议,
采纳答案by Cogwheel
Sounds like you're expecting size_tto be the same as unsigned long(possibly 64 bits) when it's actually an unsigned int(32 bits). Try using %zuin both cases.
听起来您希望size_t与unsigned long(可能是 64 位)相同,而实际上是unsigned int(32 位)。尝试%zu在这两种情况下使用。
I'm not entirely certain though.
不过我并不完全确定。
回答by kennytm
Try
尝试
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
The zrepresents an integer of length same as size_t, and the PRIu32macro, defined in the C99 header inttypes.h, represents an unsigned 32-bit integer.
的z代表长度相同的整数size_t,和PRIu32宏,在C99标头中定义inttypes.h,表示一个无符号的32位整数。
回答by u0b34a0f6ae
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. longis at least 32 bits, so %lutogether with (unsigned long)kis always correct:
所需要的只是格式说明符和类型一致,并且您总是可以强制转换以使其成为现实。long至少是 32 位,所以%luwith(unsigned long)k总是正确的:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_tis trickier, which is why %zuwas added in C99. If you can't use that, then treat it just like k(longis the biggest type in C89, size_tis very unlikely to be larger).
size_t比较棘手,这就是为什么%zu在 C99 中添加的原因。如果你不能使用它,那么就像对待它一样k(long是 C89 中最大的类型,size_t不太可能更大)。
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printfwill do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
如果您没有为您传递的类型获得正确的格式说明符,那么printf将相当于从数组中读取过多或过少的内存。只要您使用显式强制转换来匹配类型,它就是可移植的。
回答by R.. GitHub STOP HELPING ICE
If you don't want to use the PRI* macros, another approach for printing ANYinteger type is to cast to intmax_tor uintmax_tand use "%jd"or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.
如果您不想使用 PRI* 宏,则打印任何整数类型的另一种方法是分别转换为intmax_toruintmax_t和使用"%jd"or %ju。这对于没有定义 PRI* 宏的 POSIX(或其他操作系统)类型特别有用,例如off_t.

