我正在使用具有此结构的多个程序员之间共享的文件:
typedef struct _APPLE{
ULONG appleID;
struct{
ULONG isBig: 1;
ULONG isRed: 1;
ULONG isFresh: 1;
ULONG isGood: 1;
ULONG bReserved: 28;
};
}APPLE;
由于文件是共享的,我无法编辑它。我想在我的代码中使用这个APPLE结构,并希望为每个成员提供值。我怎么能这样做?
答案 0 :(得分:2)
首先,你不能在标准C中使用匿名嵌套结构,它是某些编译器使用的扩展。
所以你必须命名你的位字段结构:
typedef struct _APPLE{
ULONG appleID;
struct{
ULONG isBig: 1;
ULONG isRed: 1;
ULONG isFresh: 1;
ULONG isGood: 1;
ULONG bReserved: 28;
} flags;
}APPLE;
然后只需使用普通的点符号来访问字段:
APPLE apple;
apple.appleID = 5;
apple.flags.isBig = 1;
apple.flags.isRed = 0;
虽然位字段的多个成员可能共享相同的int
,但它们仍然彼此分离。因此,更改位域的一个成员不会改变任何其他成员。
答案 1 :(得分:0)
根据 ISO / IEC 9899:2011 ,§6.7.2.1结构和联合说明符
An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.