无法打印signed int类型的sizeof

Nic*_*Guy 3 c c++

为什么当我尝试这样做时:

#include <stdio.h>

int main()
{

    printf("Size of int: %d bytes\n",sizeof(int));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我懂了:

warning: format "%d" expects argmuments of int type, but the second argument is of type "long unsigned int..."
Run Code Online (Sandbox Code Playgroud)

(?)

如果它重要,我的操作系统是64位12.4版的Ubuntu.编译器是:GNU GCC编译器,IDE是Code :: Blocks.

为了好奇,我在另一台机器运行相同的代码,运行一个可怜的Win7,结构也是64位,我得到的结果是int的大小,而不是像上面的警告.

oua*_*uah 9

这是正确的方法:

printf("Size of int: %zu bytes\n", sizeof(int));
Run Code Online (Sandbox Code Playgroud)

sizeof运算符产生类型的值,size_t并且%zu是打印类型值的正确转换规范size_t.

如果你有一个不支持c99或c11的编译器,你可以这样做:

printf("Size of int: %lu bytes\n", (unsigned long) sizeof(int));
Run Code Online (Sandbox Code Playgroud)