This question already has answers here:
Closed 2 years ago.
Struct variable doesn't changed by assignment
(3个答案)
为什么下面的代码输出是-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));
}

最佳答案

编译时启用所有警告,并阅读编译器的说明:

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
正如您在answer中看到的。
因此,如果改用此结构:
struct st
{
        int a:2;
        int b:3;
};

你会得到想要的输出。
这也给了一个很好的解释。

10-07 16:45