Alignment in nested struct/union

151 views Asked by At

I have the structure below compiled by 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;

In the watch window:

&strct.a    = 0x0019ff0c
&strct.b    = 0x0019ff0d
&strct.c    = 0x0019ff0e
&strct.d    = 0x0019ff10   // <- Why not 0x0019ff0f ?

Thanks.

1

There are 1 answers

0
0___________ On

You cant get the reference of the bitfield in C.

But answering your question - padding is added and the compiler is free to add any padding. To avoid it you should pack your structure using compiler extensions

#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