22

我已经搜索过这个警告,每个人的代码都有一些错误,但这里有一些非常意想不到的东西,我无法弄清楚。我们确实希望 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]

我在 fn_product 中的代码——

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

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

4

3 回答 3

37

你检查了手册页吗? 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.
于 2012-10-13T18:10:43.683 回答
-1

使用“%ld”而不是“%d”。

printf("%ld", strlen(ch));
于 2021-04-15T03:26:16.243 回答
-2

Add (int) to your code, it should fix the error:

printf("\nlength of string--%d\n", (int)strlen(x))
于 2015-02-12T18:46:32.357 回答