C 中位域的内存布局 - 无法理解输出

hal*_*bra 2 c c++ memory bit-fields output

我有这个代码 - http://ideone.com/sXhWxf

#include <stdio.h>

int main(void) {

struct bitfield{
    unsigned a:5;
    unsigned c:5;
    unsigned b:6;
} bit = {1,3,3};

char *p = (char*)&bit;
printf("%d\n",*p);
p++;
printf("%d\n",*p);
// I assumed that the bits are laid out in the below order in the memory.
// Spaces are just for clarity
// 00001 00011 000011
// Also, I asumed that the 'char' will take 8 bits. But I can't understand output.
// According to me the output should be - 8 195 (considering the 1st 8 bits & 
// last eight bits for the printf statements)
return 0;
Run Code Online (Sandbox Code Playgroud)

}

输出是 -

97
12
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我详细了解此输出吗?(请阅读代码中的注释)

另外,我在Wikipedia上看到了这条语句,它说“位域的成员没有地址,因此不能与 address-of (&) 一元运算符一起使用。sizeof 运算符可能不适用于位域。 " 但我能够访问'bit'变量的地址。那个怎么样?我没有正确解释该声明吗?请指导我。

Ton*_*nyK 5

假设目标机器上的整数是 32 位,编译器已经布置了这样的bit结构:

bit 31                            bit 0
|                                 |
xxxxxxxxxxxxxxxx bbbbbb ccccc aaaaa
Run Code Online (Sandbox Code Playgroud)

其中x位未使用。

随着a=1, c=3, b=3,这变成

0000000000000000 000011 00011 00001
Run Code Online (Sandbox Code Playgroud)

拆分成字节:

00000000 00000000 00001100 01100001
Run Code Online (Sandbox Code Playgroud)

十进制:

0 0 12 97
Run Code Online (Sandbox Code Playgroud)

当存储为小端整数时,字节顺序为97 12 0 0,这解释了您的输出。

至于您的第二个问题:您正在获取bit结构的地址,而不是其任何位域的地址。char *p = (char*)&bit.a;不会工作。