Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat]

Tags:

I have searched about this warning and everyone had some mistake in their code, but here is something very unexpected I could not figure out . We do expect strlen(x) to be an integer but what does this warning tell me? How couldn't strlen be int?

In function ‘fn_product’:
line85:3:warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat]

My code in fn_product --

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

Shouldn't strlen(x) be int.Why does it say to be of format size_t?

like image 677
Optimus Prime Avatar asked Oct 13 '12 18:10

Optimus Prime


1 Answers

Did you check the man page? strlen(3) returns size_t. Use %zu to print it.

As mentioned in the comments below, clang is sometimes helpful with finding better error messages. clang's warning for exactly this case is pretty great, in fact:

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.
like image 56
Carl Norum Avatar answered Sep 30 '22 00:09

Carl Norum