2014-01-15 207 views
14

我總是收到編譯警告,但我不知道如何解決它:「%d」需要類型「詮釋」的說法,但參數2的類型爲「長unsigned int類型」 [-Wformat =]

'%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [ 

程序運行正常,但我仍然得到編譯警告:

/* Sizeof.c--Program to tell byte size of the C variable */ 
#include <stdio.h> 

int main(void) { 
    printf("\nA Char is %d bytes", sizeof(char)); 
    printf("\nAn int is %d bytes", sizeof(int)); 
    printf("\nA short is %d bytes", sizeof(short)); 
    printf("\nA long is %d bytes", sizeof(long)); 
    printf("\nA long long is %d bytes\n", sizeof(long long)); 
    printf("\nAn unsigned Char is %d bytes", sizeof(unsigned char)); 
    printf("\nAn unsigned int is %d bytes", sizeof(unsigned int)); 
    printf("\nAn unsigned short is %d bytes", sizeof(unsigned short)); 
    printf("\nAn unsigned long is %d bytes", sizeof(unsigned long)); 
    printf("\nAn unsigned long long is %d bytes\n", 
      sizeof(unsigned long long)); 
    printf("\nfloat is %d bytes", sizeof(float)); 
    printf("\nA double is %d bytes\n", sizeof(double)); 
    printf("\nA long double is %d bytes\n", sizeof(long double)); 

    return 0; 

} 

回答

23

sizeof回報size_t你需要使用%zu格式字符串,而不是%d。類型無符號整數的size_t可以變化(取決於平臺),也有可能長UNSIGNED INT無處不在,這是包括在C99標準部草案6.5.3.4sizeof運算段落:

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in (and other headers).

還要注意的是使用了錯誤的格式說明符printf是不確定的行爲,這是覆蓋在部分7.19.6.1fprintf函數,其中還包括printf瓦特第i尊重格式說明說:

If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

更新

Visual Studiodoes not support the z format specifier

The hh, j, z, and t length prefixes are not supported.

在這種情況下,正確的格式說明會%Iu

+0

在Windows上的GCC 4.8.1中,出現錯誤:「printf'ing%zu時格式爲」未知轉換類型字符'z'。 –

+0

@CzarekTomczak更新了答案,可能與此有關。 –

+0

謝謝Shafik。不幸的是,這不是跨平臺的。我必須將size_t轉換爲(unsigned long),以使代碼可以在Linux和Windows上運行。在Linux上使用%Iu(I as Integer)時出現錯誤「format'%u'期望類型爲'unsigned int'的參數」。 –

5

編譯器警告您可能會損失精度。也就是說,您用來打印sizeof,%d的格式說明符無法打印整個範圍的size_t。將%d更改爲%zu,您的警告將消失。

0

我在Linux中遇到了同樣的問題。相同的程序在windows中運行時沒有錯誤(意思是'%d'沒有錯誤),但是對於linux,我必須用'%lu'替換所有'%d'來運行程序。

相關問題