In depth understanding of the use of placeholders in structures

  • 2020-04-02 00:52:53
  • OfStack


typedef union
{
    struct x{
    char a1 : 2;
    char b1 : 3;
    char c1 : 3;
    }x1;
    char c;
}my_un;
int main()
{
    my_un a;
    a.c = 100;
    printf("%d/n",a.x1.c1);
    printf("%d/n",sizeof(my_un));

    return 0;
} 

Output results:
3
1
So the first one is 3, and the size of the combination is 1    
Analysis:
Sizeof is 1 for 1 byte, and the placeholder colon for the number of bits in the structure is actually 3+3+2=8 bits which is 1 byte

100 - > 01100100
The data for the structure in the common is also 100.
A1 is 2 lower (00);
B1 is 3 to 5 lower (001);
C1 occupies 3 higher positions (011);
So the print value of a.x1.c1 is 3.
Sizeof (my_un);
The size of the bytes Shared depends on the largest member. They are all 1(2+3+3=8 bits for structures, 1 byte for char).
So to 1.

Related articles: