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

标签 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 = %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.

回想一下

a signed 1 bit variable can hold only two values, -1 and 0

正如您在此 answer 中看到的那样.

因此,如果您改为使用此结构:

struct st
{
        int a:2;
        int b:3;
};

您将获得所需的输出。


answer也给出了很好的解释。

关于c - 为什么下面代码的输出是-1和-2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889846/

相关文章:

C open() 函数失败。难道是我的参数不对?

Swift 2.0 - 将元组结构传递给函数

c - 纯油-C。我如何解释这个c结构

c++ - 返回对位域的访问类型

c# - 使用标志枚举的优点和缺点是什么?

c - K&R 1.5.4,任何人都可以解释一下这个代码示例中的 else if 吗?

c - 如何在嵌入式 C 代码库中查找与数据一致性相关的问题?

python - 调用 PyArray_DATA 后 DECREF'ing

c++ - 如何声明在不同文件中定义的类类型的成员

c++ - 在 C++ 类中使用位域的未对齐属性