问题描述
我有以下由 VC 2005 编译的结构:
typedef struct
{
unsigned int a :8;
unsigned int b :8;
unsigned int c :8;
union
{
unsigned int val1 :8;
unsigned int val2 :8;
} d;
} MyStruct_T;
MyStruct_T strct;
在观察窗口中:
&strct.a = 0x0019ff0c
&strct.b = 0x0019ff0d
&strct.c = 0x0019ff0e
&strct.d = 0x0019ff10 // <- Why not 0x0019ff0f ?
谢谢。
解决方法
您无法在 C 中获取位域的引用。
但是回答您的问题 - 添加了填充并且编译器可以自由添加任何填充。为了避免它,你应该使用编译器扩展来打包你的结构
#include <stdio.h>
typedef struct
{
unsigned int a :8;
unsigned int b :8;
unsigned int c :8;
union
{
unsigned int val1 :8;
unsigned int val2 :8;
} d;
} MyStruct_T;
typedef struct
{
unsigned int a :8;
unsigned int b :8;
unsigned int c :8;
union
{
unsigned int val1 :8;
unsigned int val2 :8;
} d;
} __attribute__((packed)) MyStruct_T1;
MyStruct_T strct;
MyStruct_T1 strct1;
int main(void)
{
printf("%zu\n",sizeof(strct));
printf("%zu\n",sizeof(strct1));
}