1

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.

tblum
  • 153
  • 6
  • 2
    A lot of guessing here. Please state the size of `unsigned int` in your environment. – Yunnosch Feb 07 '21 at 14:24
  • 2
    Bitfields can be troublesome: they can slow things down, and bulk up executable code to access them. You shouldn't be able to get the address of them, although you seem to have gotten away with it. If you're trying to get well-defined int sizes, look into [stdint.h](https://www.cplusplus.com/reference/cstdint/) instead. – Perette Feb 07 '21 at 14:39
  • 1
    @Perette And bit-fields are also entirely implementation-defined and completely non-portable because of that. You can't rely on the order of the bit-fields nor how they get placed in a `struct`. – Andrew Henle Feb 07 '21 at 14:51

1 Answers1

0

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

0___________
  • 60,014
  • 4
  • 34
  • 74