Bit fields in C with a structure containing a union of structures

Hm ... why is it that when I print sizeof(struct MyStruct)it gives 3 (instead of 2) for this code?

#pragma pack(push, 1)
    struct MyStruct
    {
        unsigned char a : 6;
        union
        {
            struct
            {
                unsigned int b : 9;
            };
        };
    };
#pragma pack(pop)

In case that matters, I run MinGW GCC 4.5.0 on Windows 7 x64, but frankly, the result is so strange for me that I don’t think that the compiler and OS are too many here.: \

+3
source share
2 answers

You cannot have a field starting with an address that is not byte aligned. You expect:

6 bits + 9 bits -> 15 bits -> 2 bytes

but you get:

6 bits -> 1 byte
9 bits -> 2 bytes
total ->  3 bytes

Data is saved as:

| 1 byte | 2 byte |3 byte | 
 aaaaaaXX bbbbbbbb bXXXXX  

when did you expect:

| 1 byte | 2 byte |
 aaaaaabb bbbbbbbX  

edit: To clarify, based on the comments below:

( struct) . , 9 , union/struct - 16 . , :

struct MyStruct
{
    unsigned char a : 6;
    union
    {
        struct
        {
            unsigned int b : 9;
        } c:9;
    } d:9;
};

C .

+13

@nss - , , :

#include <stdlib.h>

struct Test {
  unsigned short x : 6;
  unsigned short y : 1;
  unsigned short z;
};

int main( int argc, char *argv[] ) {
  printf( "sizeof( Test ) = %d\n", sizeof( struct Test ) );

  return 0;
}

"4" . gcc, g++ Sun Studio CC cc.

, , , , , , . ( ) , :

struct Test {
  unsigned short x1 : 6;
  unsigned short x2 : 3;
                    : 1; // unused
  unsigned short x3 : 4;
  // ...
};

, ... .

: ( ) , , , , .

0

Source: https://habr.com/ru/post/1793333/


All Articles