2014-01-15 164 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'来运行程序。

相关问题