格式'%d'需要类型为'int'的参数,但参数2的类型为'size_t'[-Wformat]

Opt*_*ime 20 c strlen

我已经搜索了这个警告,并且每个人在他们的代码中都有一些错误,但这是一个非常意外的事情,我无法弄清楚.我们确实期望strlen(x)是一个整数,但这个警告告诉我什么?strlen怎么可能不是int?

In function ‘fn_product’:
line85:3:warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat]
Run Code Online (Sandbox Code Playgroud)

我在fn_product中的代码 -

char *fn_product (char x[],char y[]){
  if (strlen(x)==1)    // line85
    printf("\nlength of string--%d\n", strlen(x));
  /*other code*/
}
Run Code Online (Sandbox Code Playgroud)

不应该strlen(x)为int.为什么它的格式为size_t?

Car*_*rum 31

你查看了手册页吗? strlen(3)回报size_t.使用%zu打印.

正如下面的评论中所提到的,clang有时有助于找到更好的错误消息.clang对这种情况的警告非常棒,实际上:

example.c:6:14: warning: format specifies type 'unsigned int' but the argument
      has type 'size_t' (aka 'unsigned long') [-Wformat]
    printf("%u\n", strlen("abcde"));
            ~^     ~~~~~~~~~~~~~~~
            %zu
1 warning generated.
Run Code Online (Sandbox Code Playgroud)

  • @optimist更改编译器是错误的策略.写出正确的代码. (6认同)
  • @Kevin - `z`长度修饰符是标准C99(7.19.6.1第7段)的一部分. (3认同)
  • @optimist,正如你在上面的警告信息中看到的那样,`size_t`是一个`unsigned long`(至少在我的机器上).定期整数促销在进行比较时会发生,例如你所描述的那样,所以应该没有问题.`%zu`肯定是一个整数格式 - 这就是`u`的用途.`z`只是`size_t`的便携式大小修饰符.您可以在我的示例中使用`%lu`,但它的可移植性较差(例如,假设`size_t`是`unsigned int`的机器). (2认同)