gpt4 book ai didi

c - 如维基百科上的某些 C 代码所示,是否在 printf 格式字符串中使用了 %zu 正确的语法?

转载 作者:太空狗 更新时间:2023-10-29 17:06:31 25 4
gpt4 key购买 nike

我刚刚在维基百科上找到这段代码。
链接:http://en.wikipedia.org/wiki/Sizeof#Use

代码:

/* the following code illustrates the use of sizeof 
* with variables and expressions (no parentheses needed),
* and with type names (parentheses needed)
*/

char c;

printf("%zu,%zu", sizeof c, sizeof(int));

它声明:“应该使用 z 前缀来打印它,因为实际大小在每个体系结构上可能不同。”

我在我的编译器上试过了,但它给出了以下结果:

zu,zu

最佳答案

是的,语法是正确的(至少对于 C99)。看起来你的编译器没有设置来处理它。只需取出 z 就可以了。为了正确起见,请确保您的 printf 格式说明符与类型的大小相匹配。打开你的编译器会给你的所有警告可能在这方面有所帮助。

您的报价:

The z prefix should be used to print it, because the actual size can differ on each architecture

指的是 size_t(由 sizeof 运算符返回的类型)可能因架构而异。 z 旨在使您的代码更具可移植性。但是,如果您的编译器不支持它,那就行不通了。只需摆弄 %u%lu 等的组合,直到您获得有意义的输出。

关于c - 如维基百科上的某些 C 代码所示,是否在 printf 格式字符串中使用了 %zu 正确的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2930687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com