让我们考虑以下代码
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct bf_{
unsigned x:4;
unsigned y:4;
unsigned z:4;
unsigned w:4;
}bf;
int main(){
unsigned short i=8;
unsigned short j=9;
bf* bitfields=(bf *)&i;
bf*bit=(bf*)&j;
bitfields->w=12;
printf("%d\n",bitfields->x);
printf("%d\n",bit->y);
printf("%d\n",bitfields->w);
return 0;
}
这个片段
unsigned short j=9;
bf*bit=(bf*)&j;
printf("%d\n",bit->y);
我在猜测后添加了一些有趣的代码特征,例如在这个地方之后
bf* bitfields=(bf *)&i;
当我们写printf("%d\n",bitfields->x);
which prints 8 我明白使用指针和引用 i 的值将被授予 x 所以它打印 8 例如当我们写它时bitfiled->y
它写 0 所以我决定引入第二个元素变量 j 创建 bf 结构的新实例和引用 j 之后的语句 bit->y 应该写 9 因为据我了解它是订单定义但它给了我 0 为什么?请解释一下这段代码是如何工作的?我不会说英语,所以请原谅我的英语不好