gpt4 book ai didi

c - 位域和存储单元

转载 作者:行者123 更新时间:2023-12-01 12:39:45 24 4
gpt4 key购买 nike

我对在 64 位机器上使用 32 位编译器 (GCC MinGW) 的编译器有疑问。当我使用这个结构时:

struct S 
{
unsigned int a : 2;
unsigned int b : 3;
unsigned int c : 4;
_Bool d : 1;
} s;

sizeof s 返回 8,因此我的编译器使用我的 8 字节(64 位)机器字来打包位字段。为什么编译器是 32 位的?事实上 sizeof(int) 给我 4。

此外,如果我将我的结构声明为:

struct S 
{
char a;
char b;
char c;
_Bool d;;
} s;

sizeof s 给我 4 所以最好以这种方式打包结构以节省更多空间。人们常说使用带结构的位域可以节省空间……但我认为情况并非总是如此……我是否遗漏了一些信息?

最佳答案

位域在很大程度上是实现定义的,甚至是未指定的。

我的猜测是,从 unsigned int 切换到 _Bool 会使您的编译器启动一个全新的位域。

无论如何,您的最终解决方案是正确的:
如果您想要可靠和/或便携的东西,请自己打包。

这里是 C99+修正案 (n1570) 的所有相关部分。

6.7.2.1 Structure and union specifiers

[...]
5 A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
[...]
10 10 A bit-field is interpreted as having a signed or unsigned integer type consisting of the specified number of bits.125) If the value 0 or 1 is stored into a nonzero-width bit-field of type _Bool, the value of the bit-field shall compare equal to the value stored; a _Bool bit-field has the semantics of a _Bool.
11 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.
12 A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.126) As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bitfield, if any, was placed.
[...]
15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
[...]

关于c - 位域和存储单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26061133/

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