1

我有以下由 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 ?

谢谢。

4

1 回答 1

0

您无法在 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

于 2021-02-07T14:29:36.420 回答