的sizeof()的返回值我有以下代碼:正確的格式說明在C
#include<stdio.h>
int main()
{
printf("The 'int' datatype is \t\t %lu bytes\n", sizeof(int));
printf("The 'unsigned int' data type is\t %lu bytes\n", sizeof(unsigned int));
printf("The 'short int' data type is\t %lu bytes\n", sizeof(short int));
printf("The 'long int' data type is\t %lu bytes\n", sizeof(long int));
printf("The 'long long int' data type is %lu bytes\n", sizeof(long long int));
printf("The 'float' data type is\t %lu bytes\n", sizeof(float));
printf("The 'char' data type is\t\t %lu bytes\n", sizeof(char));
}
,輸出:
The 'int' datatype is 4 bytes
The 'unsigned int' data type is 4 bytes
The 'short int' data type is 2 bytes
The 'long int' data type is 8 bytes
The 'long long int' data type is 8 bytes
The 'float' data type is 4 bytes
The 'char' data type is 1 bytes
但是,這只是事情,編譯器要求我使用%lu
(long unsigned int)而不是%d
(int),正如我所預料的那樣。畢竟,我們只是在討論單個數字的數字,對嗎?那麼爲什麼我在使用%d
而不是%lu
時出現以下錯誤?與我在64位系統上(Ubuntu 14.10)有什麼關係?
helloworld.c: In function ‘main’:
helloworld.c:5:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'int' datatype is \t\t %d bytes\n", sizeof(int));
^
helloworld.c:6:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'unsigned int' data type is\t %d bytes\n", sizeof(unsigned int));
^
helloworld.c:7:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'short int' data type is\t %d bytes\n", sizeof(short int));
^
helloworld.c:8:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'long int' data type is\t %d bytes\n", sizeof(long int));
^
helloworld.c:9:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'long long int' data type is %d bytes\n", sizeof(long long int));
^
helloworld.c:10:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'float' data type is\t %d bytes\n", sizeof(float));
^
helloworld.c:11:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("The 'char' data type is\t\t %d bytes\n", sizeof(char));
^
Compilation finished successfully.
'sizeof'產生一個'size_t'類型的數字。它的結果是否適合'int'並不重要 - 它是這樣定義的。不要使用'%lu',因爲它不可移植 - 'size_t'的(always-)正確格式說明符是'%zu'。 – 2014-12-04 14:06:10
可能重複[如何打印大小\ _t變量portably?](http://stackoverflow.com/questions/2524611/how-to-print-size-t-variable-portably) – 2014-12-04 14:06:40