c - “%d”需要类型为 'int' 的参数,但参数 2 的类型为 'long unsigned int' [-Wformat=]

标签 c compilation printf sizeof

<分区>

我不断收到编译警告,但我不知道如何解决:

'%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [

程序运行良好,但我仍然收到编译警告:

/* Sizeof.c--Program to tell byte size of the C variable */
#include <stdio.h>

int main(void) {
    printf("\nA Char is %d bytes", sizeof( char ));
    printf("\nAn int is %d bytes", sizeof( int ));
    printf("\nA short is %d bytes", sizeof( short ));
    printf("\nA long is %d bytes", sizeof( long ));
    printf("\nA long long is %d bytes\n", sizeof( long long ));
    printf("\nAn unsigned Char is %d bytes", sizeof( unsigned char ));
    printf("\nAn unsigned int is %d bytes", sizeof( unsigned int));
    printf("\nAn unsigned short is %d bytes", sizeof( unsigned short ));
    printf("\nAn unsigned long is %d bytes", sizeof( unsigned long ));
    printf("\nAn unsigned long long is %d bytes\n",
            sizeof( unsigned long long ));
    printf("\nfloat is %d bytes", sizeof( float ));
    printf("\nA double is %d bytes\n", sizeof( double ));
    printf("\nA long double is %d bytes\n", sizeof( long double ));

    return 0;

}

最佳答案

sizeof 返回 size_t 您需要使用 %zu 作为格式字符串而不是 %dsize_tunsigned integer 的类型可能会有所不同(取决于平台)并且可能不会到处都是long unsigned int,这在草案中有所涵盖C99 标准部分 6.5.3.4 The sizeof operator paragraph 4:

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in (and other headers).

另请注意,为 printf 使用错误的格式说明符是未定义的行为,这在 7.19.6.1 fprintf 函数 部分中有介绍,其中还涵盖了关于格式说明符的 printf 说:

If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

更新

Visual Studio does not support the z format specifier :

The hh, j, z, and t length prefixes are not supported.

在这种情况下正确的格式说明符是 %Iu

关于c - “%d”需要类型为 'int' 的参数,但参数 2 的类型为 'long unsigned int' [-Wformat=],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128092/

相关文章:

c - qsort 结构中的结构数组

c - 无法将 libavformat/ffmpeg 与 x264 和 RTP 同步

c - 尝试创建这种二十一点类型的游戏。无法让 printf 工作

c++ - 对 `uuid_generate@UUID_1.0' 的 undefined reference

c - ELF文件在嵌入式系统中的使用?

c++ - printf 函数参数之间的序列点;转换之间的顺序点重要吗?

c - 意外输出 printf 语句

c - 使用 Green Hills 编译器将静态库与 header 链接起来

GWT 编译 - 为什么只有一个 user.agent 选项后仍然有 5 个排列?

c++ - fprintf、字符串和 vector