如何与位域结构体的大小确定/测量的? [英] How is the size of a struct with Bit Fields determined/measured?
问题描述
#include <stdio.h>
typedef struct size
{
unsigned int a:1;
unsigned int b:31;
unsigned int c:1;
} mystruct;
int main()
{
mystruct a;
printf("%d", sizeof(a));
return 0;
}
- 在
INT B:31
,输出为8 - 在
INT B:1
,输出为4 - 在
INT B:32
,输出为12 - With
int b:31
, the output is 8. - With
int b:1
, the output is 4. - With
int b:32
, the output is 12.
有人能解释一下原因?
推荐答案
您不说你知不知道位域是什么,但我会假设你做的。
You don't say whether you know what bitfields are, but I'll assume you do.
在您的实现,显然 unsigned int类型
是一个32位整数,占用4个字节。这占第一和第二实施例。显然,3位域共33位不适合单个 unsigned int类型
,因此在第一个例子中的8个字节的需要。 3位域共3位当然不适合的 unsigned int类型
,因此只有4中的第二个例子字节。
On your implementation, evidently unsigned int
is a 32 bit integer, occupying 4 bytes. This accounts for the first and second examples. Clearly 3 bitfields totalling 33 bits don't fit into a single unsigned int
, hence the need for 8 bytes in the first example. 3 bitfields totalling 3 bits certainly do fit into an unsigned int
, hence only 4 bytes in the second example.
此外,位域不能跨越多个整数。这占了第三示例。我不记得是否这就是标准的要求,或者您的实现只是一个细节。无论哪种方式,因为 B
是32位,它填补了整个 unsigned int类型
自身,迫使这两个<$的C $ C> A 和 C
来占据自己的 unsigned int类型
,前后中间的一个。因此,12个字节。
Furthermore, a bitfield cannot span multiple integers. This accounts for the third example. I can't remember whether that's a requirement of the standard, or just a detail of your implementation. Either way, since b
is 32 bits, it fills a whole unsigned int
on its own, forcing both of a
and c
to occupy their own unsigned int
, before and after the middle one. Hence, 12 bytes.
这篇关于如何与位域结构体的大小确定/测量的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!