为什么有些结构体具有零宽度的位域,以及为什么需要它?这个问题似乎与Practical Use of Zero-Length Bitfields类似。
以上程序的输出是:
请解释为什么这些值是负数,以及结构体内这些变量的内存布局是怎样的?
struct foo {
int a:3;
int b:2;
int :0; // Force alignment to next boundary.
int c:4;
int d:3;
};
int main()
{
int i = 0xFFFF;
struct foo *f = (struct foo *)&i;
printf("a=%d\nb=%d\nc=%d\nd=%d\n", f->a, f->b, f->c, f->d);
return 0;
}
以上程序的输出是:
manav@os-team:~/programs/test$ ./a.out
a=-1
b=-1
c=-8
d=0
请解释为什么这些值是负数,以及结构体内这些变量的内存布局是怎样的?
d
的值都会不同。然而,在Windows mingw 5.3下输出将保持不变。因此,它在很大程度上取决于编译器。 - Lewis Chan