printf格式字符串警告长无符号整数

时间:2012-02-16 20:08:32

标签: c linux

我的c代码有问题,当我尝试printf相同的值时,g ++编译器会给出一个关于long unsigned int的错误。这是我的代码和我得到的错误:

as3.c: warning: format %s expects type char *, but argument 2 has type onion
as3.c: warning: format %d expects type int, but argument 3 has type long unsigned int
as3.c: warning: format %d expects type int, but argument 3 has type long unsigned int
as3.c: warning: format %d expects type int, but argument 5 has type long unsigned int
as3.c: warning: format %d expects type int, but argument 2 has type long unsigned int
#define NUM1 5.557111111111111
#define NUM2 1937006915
#define NUM3 1668248096
#define NUM4 8555

#include <stdio.h>

typedef union {
char  * a;
double num;
int * i;
}onion;

int main(int argc, char ** argv)
{
onion myoni;
char array[] = "TESTING";
int array2[] = { NUM2, NUM1, NUM3 };
myoni.a = array; 
printf("char: %s, %d\n",myoni,sizeof(myoni.a));
myoni.num = NUM1; 
printf("double: %10.15f, %d\n", myoni.num, sizeof(myoni.num));
myoni.i = array2;
printf("int: %d %d %d, %d\n", myoni.i[0], myoni.i[1],myoni.i[2], sizeof(myoni.i));

    return 0;
}

4 个答案:

答案 0 :(得分:5)

而不是:

printf("char: %s, %d\n",myoni,sizeof(myoni.a));

使用:

printf("char: %s, %zu\n",myoni.a,sizeof(myoni.a));

也就是说,为char *转换说明符传递s,并使用%zu转换规范获取sizeof运算符的结果。

答案 1 :(得分:3)

将值从sizeof转换为unsigned long(类型为size_t,在C99中,您可以使用"%zu"打印size_t类型的值)并在"%lu"说明符

中使用printf
printf("%lu\n", (unsigned long)sizeof something);
printf("%lu\n", (unsigned long)sizeof (sometype));
/* C99 below */
printf("%zu\n", sizeof something);
printf("%zu\n", sizeof (sometype));

类型onion的成员类型为char*。我怀疑那是你想打印的东西

printf("%s\n", myoni.a);

答案 2 :(得分:0)

对于第一个警告,请不要像onion那样使用onion.a

    #define NUM1 5.557111111111111
    #define NUM2 1937006915
    #define NUM3 1668248096
    #define NUM4 8555

    #include <stdio.h>

    typedef union
    {
      char * a;
      double num;
      int * i;
    } onion;

    int main(int argc, char ** argv)
    {
      onion myoni;
      char array[] = "TESTING";
      int array2[] =
      { NUM2, NUM1, NUM3 };
      myoni.a = array;
      printf("char: %s, %d\n", myoni.a, sizeof(myoni.a));
      myoni.num = NUM1;
      printf("double: %10.15f, %d\n", myoni.num, sizeof(myoni.num));
      myoni.i = array2;
      printf("int: %d %d %d, %d\n", myoni.i[0], myoni.i[1], myoni.i[2],
          sizeof(myoni.i));

      return 0;
    }

答案 3 :(得分:0)

第一个警告是由于这一行:

printf("char: %s, %d\n",myoni,sizeof(myoni.a));

%s期望类型为char *,但您已传递了onion类型的变量。您需要明确使用a的{​​{1}}成员,其成员类型为myoni

char *

第二个警告是由于使用了printf("char: %s, %d\n",myoni.a,sizeof(myoni.a)); 宏,它返回sizeof,如警告消息中所述。 long unsigned int的格式说明符为long unsigned int(长无符号),而非%lu。即:

%d