C 为什么下面代码的输出是-1和-2?

C 为什么下面代码的输出是-1和-2?,c,struct,bit-fields,C,Struct,Bit Fields,为什么下面代码的输出是-1和-2,它应该是1和2,对吗 同样在64位服务器上,下面的结构大小是4字节,应该是8字节,对吗 #include<stdio.h> struct st { int a:1; int b:2; }; main() { struct st obj={1,2}; printf("a = %d\nb = %d\n",obj.a,obj.b); printf("Size of struct

为什么下面代码的输出是-1和-2,它应该是1和2,对吗

同样在64位服务器上,下面的结构大小是4字节,应该是8字节,对吗

#include<stdio.h>
struct st
{
        int a:1;
        int b:2;
};
main()
{
        struct st obj={1,2};
        printf("a = %d\nb = %d\n",obj.a,obj.b);
        printf("Size of struct = %d\n",sizeof(obj));
}
#包括
结构街
{
INTA:1;
INTB:2;
};
main()
{
struct st obj={1,2};
printf(“a=%d\nb=%d\n”,对象a、对象b);
printf(“结构的大小=%d\n”,sizeof(obj));
}

在启用所有警告的情况下编译,并阅读编译器的说明:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^
main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value
      from 2 to -2 [-Wbitfield-constant-conversion]
        struct st obj={1,2};
                         ^
main.c:11:40: warning: format specifies type 'int' but the argument has type
      'unsigned long' [-Wformat]
        printf("Size of struct = %d\n",sizeof(obj));
                                 ~~    ^~~~~~~~~~~
                                 %lu
3 warnings generated.
回想一下

有符号1位变量只能包含两个值,-1和0

正如你在这张照片上看到的

因此,如果改用此结构:

struct st
{
        int a:2;
        int b:3;
};
您将获得所需的输出



这也给出了一个很好的解释。

在启用所有警告的情况下编译,并阅读编译器的说明:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^
main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value
      from 2 to -2 [-Wbitfield-constant-conversion]
        struct st obj={1,2};
                         ^
main.c:11:40: warning: format specifies type 'int' but the argument has type
      'unsigned long' [-Wformat]
        printf("Size of struct = %d\n",sizeof(obj));
                                 ~~    ^~~~~~~~~~~
                                 %lu
3 warnings generated.
回想一下

有符号1位变量只能包含两个值,-1和0

正如你在这张照片上看到的

因此,如果改用此结构:

struct st
{
        int a:2;
        int b:3;
};
您将获得所需的输出



这也给出了一个很好的解释。

你得到的答案是
-1和-2
-1和-2
?@SouravGhosh-1和-2先生“应该是1和2,对吧?”不,你为什么认为应该是这样?你得到的答案是
-1和-2
-1和2
?@SouravGhosh-1和-2先生“应该是1和2,对吧?”不,为什么你认为应该是这样?欢迎@Chirag,我用一个工作结构更新了我的答案,希望这足够让人接受!:)是的,我非常清楚这个概念,感谢您的帮助You are welcome@Chirag,我用一个工作结构更新了我的答案,希望这足以让您接受!:)是的,我非常清楚这个概念,谢谢你的帮助