含位域结构的大小 [英] size of a structure containing bit fields
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member\">Why为等于每个成员的sizeof的总和一个结构是不是和sizeof?
我是想了解位域的概念。
但我无法找到原因如下结构的案例三大小现身为8个字节。
I was trying to understand the concept of bit fields. But I am not able to find why the size of the following structure in CASE III is coming out as 8 bytes.
struct B
{
unsigned char c; // +8 bits
} b;
的sizeof(二); //输出:1(因为无符号字符把我的系统上1个字节)
sizeof(b); // Output: 1 (because unsigned char takes 1 byte on my system)
struct B
{
unsigned b: 1;
} b;
sizeof(b); // Output: 4 (because unsigned takes 4 bytes on my system)
案例三:
struct B
{
unsigned char c; // +8 bits
unsigned b: 1; // +1 bit
} b;
sizeof(b); // Output: 8
我不明白为什么输出情况III当属8.我期待1(字符)+ 4(无符号)= 5。
I don't understand why the output for case III comes as 8. I was expecting 1(char) + 4(unsigned) = 5.
推荐答案
您可以使用 offsetof
检查结构的布局,但它会沿着线的东西的:
You can check the layout of the struct by using offsetof
, but it will be something along the lines of:
struct B
{
unsigned char c; // +8 bits
unsigned char pad[3]; //padding
unsigned int bint; //your b:1 will be the first byte of this one
} b;
现在,很明显,(在32位拱)。在的sizeof(B)
将 8
,不是吗?
Now, it is obvious that (in a 32-bit arch.) the sizeof(b)
will be 8
, isn't it?
现在的问题是,为什么3个字节的填充物,而不是更多或更少?
The question is, why 3 bytes of padding, and not more or less?
答案是,在偏移字段的成一个结构具有相同的对齐方式要求的领域本身的类型。在你的架构中,整数是4字节对齐的,所以 offsetof(B,宾特)
必须是倍数4.不能为0,因为在 C
之前,所以这将是4.如果字段·宾特·
开始偏移4和4个字节长,那么的大小结构是8。
The answer is that the offset of a field into a struct has the same alignment requirements as the type of the field itself. In your architecture, integers are 4-byte-aligned, so offsetof(b, bint)
must be multiple of 4. It cannot be 0, because there is the c
before, so it will be 4. If field bint
starts at offset 4 and is 4 bytes long, then the size of the struct is 8.
看它的另一种方法是,结构的调整需求是最大的任何字段,所以这个 B
将是4字节对齐(因为它是你的位字段)。但一类型的大小必须是对准的倍数,4是不够的,因此这将是8
Another way to look at it is that the alignment requirement of a struct is the biggest of any of its fields, so this B
will be 4-byte-aligned (as it is your bit field). But the size of a type must be a multiple of the alignment, 4 is not enough, so it will be 8.
这篇关于含位域结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!