The difference between struct and union, structure and union in C language

Community union:

Make several variables of different types occupy a piece of memory.

can cover each other.

The memory size takes the length of the longest variable.

When assigning a value, other variable members are rewritten due to the shared memory.


Structure struct:

The disparate data are integrated into a whole.

Each variable has its own memory space.

The memory size is the sum of the memory occupied by all variables.


Take a chestnut :

#include <stdio.h>

typedef union {//Define a union
    int i;
    struct {
        char first;
        char second;
    } half;
} number;

int main() {
    number number;
    number.i = 0X4241;//Joint member assignment
    printf("%c%c\n", number.half.first, number.half.second);
    number.half.first = 'a'; //In union, structure member assignment
    number.half.second = 'b';
    printf("%x\n", number.i);
    return 0;
}

The output is :

AWAY

6261

Analysis :

Here the i and half structures are shared memory

number.i=0X4241 After assigning a value to i, the memory stores 0100 0010 0100 0001 in binary

corresponding to the structure in order

half.first=0100 0010 converted to decimal is 66 (asc code of letter A)

half.second=0100 0001 converted to decimal is 65 (asc code of letter B)

So the output is AB








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325807179&siteId=291194637