2014-01-15 1 views
14

나는 경고를 컴파일 점점 계속하지만 난 그것을 해결하는 방법을 모른다 :'% d'이 (가) 형 'INT'의 인수를 기대하지만, 인수 2는 유형이 '긴 부호 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 반환 대신 %d의 형식 문자열을 %zu를 사용할 필요가 size_t. 부호 정수의 형태는 size_t는 (플랫폼)에 따라 달라질 수 있고,하지 않을 수도 긴 부호 드래프트 C99 표준 섹션 6.5.3.4sizeof의 운영자 단락 4에 덮여 사방 INT :

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

또한 printf 대해 잘못된 형식 지정자를 사용하는 것은 또한 승 printf 커버 부 7.19.6.1는 fprintf 함수에 덮여 정의 동작되어 있습니다 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에서 오류가 발생합니다. "% zu을 (를) 인쇄 할 때 알 수없는 변환 유형 문자 '형식이 z'입니다. –

+0

@CzarekTomczak 업데이트 된 답변, 아마도 관련이 있습니다. –

+0

감사 Shafik. 불행히도 이것의 어느 것도 크로스 플랫폼이 아닙니다. Linux와 Windows에서 모두 작동하도록 code에 size_t를 (unsigned long) 변환해야합니다. Linux에서 % Iu (I Integer)를 사용할 때 "format '% u'형식의 인수가 'unsigned int'입니다."오류가 발생합니다. –

5

컴파일러에서 정확도가 떨어질 수 있다고 경고합니다. 즉, sizeof, %d을 인쇄 할 때 사용하는 형식 지정자는 size_t의 전체 범위를 인쇄 할 수 없습니다. %d%zu으로 변경하면 경고 메시지가 사라집니다.

0

나는 Linux에서 동일한 문제가있었습니다. 동일한 프로그램이 윈도우에서 오류없이 실행됩니다 ('% d'은 오류없이 작동했습니다.). 그러나 리눅스에서는 '% lu'를 사용하여 프로그램을 실행해야했습니다.