Understand Union in one article

Composite types in C language mainly include: structure ( struct ), union ( union ) and enumeration ( enum ). Among them, union is also called union body , which has a very similar syntax to structure body.

The difference between a union and a structure: each member of a structure occupies different memory and has no influence on each other; while all members of a union occupy the same memory, modifying one member will affect the rest.

 The following piece of code not only verifies the length of the union, but also shows that the members of the union will affect each other, and modifying the value of one member will affect other members. It occupies memory equal to the memory occupied by the longest member.

#include <stdio.h>

union data{
    int n;
    char ch;
    short m;
};

int main(){
    union data a;
    printf("%d, %d\n", sizeof(a), sizeof(union data) );
    a.n = 0x40;
    printf("%X, %c, %hX\n", a.n, a.ch, a.m);
    a.ch = '9';
    printf("%X, %c, %hX\n", a.n, a.ch, a.m);
    a.m = 0x2059;
    printf("%X, %c, %hX\n", a.n, a.ch, a.m);
    a.n = 0x3E25AD54;
    printf("%X, %c, %hX\n", a.n, a.ch, a.m);
   
    return 0;
}
4, 4
40, @, 40
39, 9, 39
2059, Y, 2059
3E25AD54, T, AD54

memory overlay technology

It can be clearly seen from the figure above that the member variables m, n, and ch are aligned to the same segment of memory: assigning a value to ch modifies the previous byte, assigning a value to m will affect the first two bytes, and assigning a value to n will affect will overwrite the entire four bytes of memory.

Guess you like

Origin blog.csdn.net/mikewzp/article/details/130762543