我正在尝试在RHEL 5.6,64位上编译以下内容,并且我不断收到警告
"var.c:7:警告:格式'%d'需要类型'int',但参数2的类型为'long unsigned int'"
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int n =10;
printf("The size of integer is %d\n", sizeof(n));
}
Run Code Online (Sandbox Code Playgroud)
如果我将"n"的声明更改为以下内容并不重要
我想要做的就是在我的机器上打印整数的大小,而不是真正关注limits.h.
Rob*_*ves 44
sizeof函数返回一个size_t类型.尝试使用%zu转换说明符而不是%d.
printf("The size of integer is %zu\n", sizeof(n));
Run Code Online (Sandbox Code Playgroud)
为了澄清,请使用%zu您的编译器是否支持C99; 否则,或者如果您想要最大的可移植性,打印size_t值的最佳方法是将其转换为unsigned long并使用%lu.
printf("The size of integer is %lu\n", (unsigned long)sizeof(n));
Run Code Online (Sandbox Code Playgroud)
这样做的原因是size_t标准保证是无符号类型; 但是标准没有规定它必须具有任何特定的大小(只要大到足以表示任何对象的大小).实际上,如果unsigned long不能代表您环境的最大对象,您甚至可能需要使用unsigned long long cast和%llu说明符.
在C99中,添加了z长度修改器以提供一种方法来指定要打印的值是size_t类型的大小.通过使用,%zu您指示正在打印的值是无符号的size_t大小值.
这是你似乎不应该考虑它的事情之一,但你做到了.
进一步阅读: