C 结构中两个不同位置的位字段
Bit-fields at two separate locations in a Structure in C
在一个结构中,我们通常有连续的位域;即,一个接一个并相邻——例如:
struct demo
{
char a;
char b:1;
char c:2;
char d:2;
int e;
} demo1;
demo1
的大小为 8 个字节:
- size =
a
(1 byte) + bit-fields(1 byte) + gap(2 bytes) + e
(4 bytes))
现在考虑以下结构:
struct demo
{
char a;
int b:1;
char c;
char d;
int e:2;
} demo1;
当我使用 sizeof(demo1)
时,它给了我 8 个字节 — 但我想知道这些位域是如何在内存中呈现的。
如果像上面那样计算结构大小应该是:
- 大小 =
a
(1 字节)+ b
(4 字节)+ c
(1 字节)+ d
(1 字节)+ e
(4字节)
在编程过程中,我们不关心如何使用 sizeof
计算大小,我们甚至不在两个不同的位置使用位域,但有时会问这类问题采访者。
连续的(非零宽度)位域可以合并到一个内存位置,而一个位域后跟一个非位域是不同的内存位置。
struct demo
{
char a;
int b:1;
char c;
char d;
int e:2;
} demo1;
所以在这个struct
中,有1个非位域和1个位域,然后是2个非位域,最后是位域。
在位域成员之后有一个非位域(或零长度位域),接下来是 different/independent 内存 location/object。
还有:
编译器不会对 struct
的元素重新排序,因为那样会违反 C 标准。 C99 标准第 6.7.2.1 节规定:
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.
在一个结构中,我们通常有连续的位域;即,一个接一个并相邻——例如:
struct demo
{
char a;
char b:1;
char c:2;
char d:2;
int e;
} demo1;
demo1
的大小为 8 个字节:
- size =
a
(1 byte) + bit-fields(1 byte) + gap(2 bytes) +e
(4 bytes))
现在考虑以下结构:
struct demo
{
char a;
int b:1;
char c;
char d;
int e:2;
} demo1;
当我使用 sizeof(demo1)
时,它给了我 8 个字节 — 但我想知道这些位域是如何在内存中呈现的。
如果像上面那样计算结构大小应该是:
- 大小 =
a
(1 字节)+b
(4 字节)+c
(1 字节)+d
(1 字节)+e
(4字节)
在编程过程中,我们不关心如何使用 sizeof
计算大小,我们甚至不在两个不同的位置使用位域,但有时会问这类问题采访者。
连续的(非零宽度)位域可以合并到一个内存位置,而一个位域后跟一个非位域是不同的内存位置。
struct demo
{
char a;
int b:1;
char c;
char d;
int e:2;
} demo1;
所以在这个struct
中,有1个非位域和1个位域,然后是2个非位域,最后是位域。
在位域成员之后有一个非位域(或零长度位域),接下来是 different/independent 内存 location/object。
还有:
编译器不会对 struct
的元素重新排序,因为那样会违反 C 标准。 C99 标准第 6.7.2.1 节规定:
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.