c - 我不明白这个 C 代码的行为(与 2 个位域结构、一个字和一个字节数组的 union )

标签 c struct unions bit-fields

我有以下 C 代码段:

typedef union _REG_CiFIFOCON {
    struct {
        uint32_t RxNotEmptyIE : 1;
        uint32_t RxHalfFullIE : 1;
        uint32_t RxFullIE : 1;
        uint32_t RxOverFlowIE : 1;
        uint32_t unimplemented1 : 1;
        uint32_t RxTimeStampEnable : 1;
        uint32_t unimplemented2 : 1;
        uint32_t TxEnable : 1;
        uint32_t UINC : 1;
        uint32_t unimplemented3 : 1;
        uint32_t FRESET : 1;
        uint32_t unimplemented4 : 13;
        uint32_t FifoSize : 5;
        uint32_t PayLoadSize : 3;
    } rxBF;

    struct {
        uint32_t TxNotFullIE : 1;
        uint32_t TxHalfFullIE : 1;
        uint32_t TxEmptyIE : 1;
        uint32_t unimplemented1 : 1;
        uint32_t TxAttemptIE : 1;
        uint32_t unimplemented2 : 1;
        uint32_t RTREnable : 1;
        uint32_t TxEnable : 1;
        uint32_t UINC : 1;
        uint32_t TxRequest : 1;
        uint32_t FRESET : 1;
        uint32_t unimplemented3 : 5;
        uint32_t TxPriority : 5;
        uint32_t TxAttempts : 2;
        uint32_t unimplemented4 : 1;
        uint32_t FifoSize : 5;
        uint32_t PayLoadSize : 3;
    } txBF;
    uint32_t word;
    uint8_t byte[4];
} REG_CiFIFOCON;

两个结构都是 32 位,因此它是字变量和字节数组(因为它由 4 个字节组成。4x8 = 32 位)。

我的问题是:我不理解这个 union 的行为。我知道如何访问每个结构体以及单词和数组中的位,但它们是如何相关的?我知道如果只有 1 个结构体和单词,将单词设置为某个值会相应地修改位字段(反之亦然),但我不知道在这种情况下会发生什么。

谢谢您,祝您有愉快的一天!

最佳答案

同一个 union 中有 4 种类型。它们都使用相同的内存。

更改其中哪一项并不重要 - 它会影响其他项。

您的类型的大小是 32 字节 - 在您的情况下,这也是其中每个类型的大小。否则 - 它将是内部最大类型的大小。

关于c - 我不明白这个 C 代码的行为(与 2 个位域结构、一个字和一个字节数组的 union ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55384481/

相关文章:

data-structures - 如何在不相交的集合数据结构中创建集合并解决并集?

c - 如何通过管道发送文件结尾而不关闭管道?

c - 不同大小成员的 union 的内存布局?

c - 当我们打印其他未初始化的变量时, union 如何工作?

objective-c - 指向 struct C/ObjC 中指针的指针

c++ - 使用构造函数初始化结构中的结构

c++ - Xcode 没有链接两个结构?

创建链表结构

c - __section( ) 在 linux 内核源代码中是什么意思

c - 需要使用数组指针、其长度和合并函数的工作空间数组在 C 中实现递归合并排序代码