C语言 printf 是否需要 %zu 说明符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41263896/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:32:29  来源:igfitidea点击:

Is the %zu specifier required for printf?

cprintfc89size-tc-libraries

提问by Trevor Hickey

We are using C89 on an embedded platform. I attempted to print out a size_t, but it did not work:

我们在嵌入式平台上使用 C89。我试图打印出一个size_t,但没有奏效:

#include <stdio.h>
int main(void) {
    size_t n = 123;
    printf("%zu\n",n);
    return 0;
}

Instead of 123, I got zu.
Other specifiers work correctly.

而不是123,我得到了zu
其他说明符正常工作。

If size_texists shouldn't zualso be available in printf?
Is this something I should contact my library vendor about, or is a library implementation allowed to exclude it?

如果size_t存在也不应该 zuprintf?
这是我应该联系我的库供应商的事情,还是允许库实现排除它?

回答by P.P

If size_t exists shouldn't zu also be available in printf?

如果 size_t 存在,则 zu 不应该在 printf 中可用吗?

size_texisted at least since C89 but the respective format specifier %zu(specifically the length modifier z) was added to the standard only since C99.

size_t至少自 C89 以来就存在,但仅自 C99 以来才将相应的格式说明符%zu(特别是长度修饰符z)添加到标准中。

So, if you can't use C99 (or C11) and had to print size_tin C89, you just have to fallback to other existing types, such as:

因此,如果您不能使用 C99(或 C11)并且不得不size_t在 C89 中打印,您只需要回退到其他现有类型,例如:

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

回答by Praveen Kumar Rana

This is working fine. In my system, it's printing the expected value. You may be getting the error due to the compiler. I am using the GCCcompiler. If you have this only and trying to get the output the first update the GCC and then try. It will work.

这工作正常。在我的系统中,它正在打印预期值。由于编译器,您可能会收到错误。我正在使用GCC编译器。如果您只有这个并尝试获取输出,请首先更新 GCC,然后尝试。它会起作用。

Your program input

你的程序输入

The output of the program

程序的输出