结构中联合的位字段

时间:2016-09-23 14:19:16

标签: c bit-fields

我有这两种结构: - 1.

typedef struct bitfield
{
    unsigned int a:16;
    unsigned int b:17;
    union
    {    
        unsigned int c:4;
        unsigned int d:32;
    };
}bfield;

这个结构有匿名联合,当我计算这个结构的大小时 - 它出来是12个字节(4 + 4 + 4)。这很好。

2

typedef struct bitfield
{
    unsigned int a:16;
    unsigned int b:17;
    union u
    {    
        unsigned int c:4;
        unsigned int d:32;
    };
}bfield;

但我的32位机器上的DevC ++编译器为这个结构的大小打印了8个字节。我不明白为什么它会成为8。

2 个答案:

答案 0 :(得分:5)

您的第一个示例声明了一个匿名union的结构。

第二个例子声明了一个结构,其中包含union的声明,这是一个noop。 E.g。

typedef struct bitfield
{
    unsigned int a:16;
    unsigned int b:17;
    union u
    {    
        unsigned int c:4;
        unsigned int d:32;
    };
}bfield;

int main(void) {
    struct bitfield b;
    b.c=2;
}

将失败

x.c:14:4: error: 'struct bitfield' has no member named 'c'

编译器可能会用

警告它
x.c:9:6: warning: declaration does not declare anything

所以,你的问题与bitfields没什么关系,但与匿名联盟有关。

答案 1 :(得分:2)

OP中的联合声明是不正确的(它不符合OP的要求)。

它看起来只是一个联合声明,并没有在结构中添加一个字段。

将union字段声明为匿名或命名。

请参阅此示例(也发布在此处:http://rextester.com/EPUEH77041

在这两种情况下,struct的大小都是12个字节。

#include <iostream>

typedef struct bitfield
{
    unsigned int a:16;
    unsigned int b:17;
    union u
    {    
    unsigned int c:4;
    unsigned int d:32;
    }U;
}bfield;


typedef struct bitfield2
{
    unsigned int a:16;
    unsigned int b:17;
    union
    {    
    unsigned int c:4;
    unsigned int d:32;
    };
}bfield2;

int main()
{
    std::cout << "Test bitfields1\n" << sizeof(bfield) << "\n";
    std::cout << "Test bitfields2\n" << sizeof(bfield2) << "\n";

    static volatile bfield y;
    y.a=0x1234;
    y.b = 0x1FF55;
    y.U.d = 0x5a5a5a5a;
    std::cout << std::hex << y.U.d << "\n";

    static volatile bfield2 x;
    x.a=0x1234;
    x.b = 0x1FF55;
    x.d = 0x5a5a5a5a;
    std::cout << std::hex << x.d << "\n";
}