gpt4 book ai didi

c - 只有位字段的结构 union ,sizeof 函数加倍字节,C

转载 作者:太空狗 更新时间:2023-10-29 16:05:21 24 4
gpt4 key购买 nike

出于某种原因,我不太明白我的仅包含位字段的结构的 union 设置的字节数是任何单个结构所需字节数的两倍。

#include <stdio.h>
#include <stdlib.h>

union instructionSet {
struct Brane{
unsigned int opcode: 4;
unsigned int address: 12;
} brane;
struct Cmp{
unsigned int opcode: 4;
unsigned int blank: 1;
unsigned int rsvd: 3;
unsigned char letter: 8;
} cmp;
struct {
unsigned int rsvd: 16;
} reserved;
};

int main() {

union instructionSet IR;// = (union instructionSet*)calloc(1, 2);

printf("size of union %ld\n", sizeof(union instructionSet));
printf("size of reserved %ld\n", sizeof(IR.reserved));
printf("size of brane %ld\n", sizeof(IR.brane));
printf("size of brane %ld\n", sizeof(IR.cmp));


return 0;
}

所有对 sizeof 的调用都返回 4,但据我所知它们应该返回 2。

最佳答案

这里有几个问题,首先,您的位域 Brane 使用的是 4 字节的 unsigned int。

即使你只使用了一半的位,你仍然使用了一个完整的 32 位宽度的 unsigned int。

其次,您的 Cmp 位域使用两种不同的字段类型,因此您对前 3 个字段使用 32 位 unsigned int 中的 8 位,然后使用 unsigned char 作为完整的 8 位。由于数据对齐规则,此结构至少为 6 个字节,但可能更多。

如果您想优化 union 体的大小以仅占用 16 位。您首先需要使用 unsigned short,然后您需要始终使用相同的字段类型以将所有内容保存在相同的空间中。

像这样的事情会完全优化你的联盟:

union instructionSet {
struct Brane{
unsigned short opcode: 4;
unsigned short address: 12;
} brane;
struct Cmp{
unsigned short opcode: 4;
unsigned short blank: 1;
unsigned short rsvd: 3;
unsigned short letter: 8;
} cmp;
struct {
unsigned short rsvd: 16;
} reserved;
};

这将使您周围的大小为 2。

关于c - 只有位字段的结构 union ,sizeof 函数加倍字节,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com