#include <stdio.h>
int main()
{
struct bitfield
{
unsigned a:5;
unsigned c:5;
unsigned b:6;
} bit;
char *ptr;
struct bitfield bit1={1,3,3};
ptr=&bit1;
ptr++;
printf("%d",*ptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个问题的输出是12.它是怎么来的?有人可以解释一下吗?我尽力解释它.
Sha*_*ain 14
这个问题的解释相当简单:
Binary value of 1 is 00001 (as "a" have 5 bitfield)
Binary value of 3 is 00011 (as "c" have 5 bitfield)
Binary value of 3 is 000011 (as "b" have 6 bitfield)
Run Code Online (Sandbox Code Playgroud)
内存布局可以看作如下:

前5位被占用a并具有值00001.然后,通过b具有值00011 来占用5位,并且通过c具有值000011 来占用最后6位.
因此,在启动时指针ptr位于内存位置1000,现在当你执行时ptr++.由于sizeof(char)是1,ptr将移动1个内存位置.因此ptr移动到存储器位置1001.
因此*ptr会给你存储在存储位置1001的值,因此答案将是12