我在Windows上的turbo C上工作,其中char占用一个字节.现在我的问题在于下面的联合.
union a
{
unsigned char c:2;
}b;
void main()
{
printf("%d",sizeof(b)); \\or even sizeof(union a)
}
Run Code Online (Sandbox Code Playgroud)
该程序打印输出为2,其中union应该只占用1个字节.为什么会这样?
对于struct,它可以很好地给出1个字节但这个联合工作不正常.
还有一件事如何访问这些位字段.
scanf("%d",&b.c); //even scanf("%x",b.c);
Run Code Online (Sandbox Code Playgroud)
没有用,因为我们不能有位的地址.所以我们必须使用下面的另一个变量
int x;
scanf("%d",&x);
b.c=x;
Run Code Online (Sandbox Code Playgroud)
我们不能避免吗?有没有其他方法???