警告:格式'%d'需要类型'int',但参数4的类型为'size_t'

时间:2013-04-28 21:56:05

标签: g++ gcc-warning netcdf

我按照一些类似的帖子来修改代码,但仍会生成警告。

$ g++ ncfile.c -o ncfile -g -lnetcdf

ncfile.c: In function ‘int main(int, char**)’:
ncfile.c:363: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘size_t’
ncfile.c:363: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘size_t’
ncfile.c:364: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘size_t’
ncfile.c:364: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘size_t’

在第363和364行的那个区块中:

  for(i = 0; i < ndimsp; i++) {
    char * temp_name;
    size_t temp_len;
    temp_name = (char *)malloc(sizeof(char) * 20);
    nc_inq_dim(cid, dimids[i], temp_name, &temp_len);
    dimlens[i] = temp_len;
    if(dimids[i] == unlimdimidp) printf("\t\t%d %s   \tlength: %d (UNLIMITED)\n", i, temp_name, temp_len);
    else printf("\t\t%d %s   \tlength: %d\n", i, temp_name, temp_len);
    total_records *= temp_len;
    free(temp_name);
  }

我该怎样摆脱警告。这对结果有害吗?

谢谢,

迈克尔

1 个答案:

答案 0 :(得分:7)

尝试使用z修饰符。对于size_t值,基本上是%zu。

这将是结果:

printf("\t\t%d %s   \tlength: %zu\n", i, temp_name, temp_len);

看看这个问题:

How can one print a size_t variable portably using the printf family?