问题
I am getting a warning warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]
I am writing a very basic program which gives the size of the data type but in the Linux environment I am getting this warning whereas in Visual Studio, the program works without any warning. The source code is as below :-
#include<stdio.h>
int main()
{
int a;
printf("\nThe Size Of Integer A Is = \t%d", sizeof(a));
return 0;
}
Answer will be appreciated and also can anyone tell me a proper way of solving such kind of warnings as I am new to this C and it's standard.
回答1:
sizeof
returns size_t
type. Use %zu
specifier to print the value of sizeof
.
printf("\nThe Size Of Integer A Is = \t%zu", sizeof(a));
C11 6.5.3.4 The sizeof
and _Alignof
operators:
5 The value of the result of both operators is implementation-defined, and its type (an
unsigned integer
type) issize_t
, defined in<stddef.h>
(and other headers).
NOTE: As loreb pointed out in his comment that when you will compile your code in Windows, then most probably you will get the warning like:
[Warning] unknown conversion type character 'z' in format [-Wformat]
[Warning] too many arguments for format [-Wformat-extra-args]
回答2:
sizeof
return size_t
and not int
Use %zu
in printf
回答3:
In C99 the correct format for a size_t variable is %zu.
Use:
printf("\nThe Size Of Integer A Is = \t%zu", sizeof(a));
来源:https://stackoverflow.com/questions/21144780/getting-warning-when-using-sizeof