嵌套结构/联合中的对齐

问题描述

我有以下由 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));
}

https://godbolt.org/z/aW36oY

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...