When I first learned the C language, I did not pay special attention to the use of Union, and I do not know what is different from struc T. After some searching on the internet, I finally realized it, so let's make a summary. If any error occurs, please correct it. (There is no big difference between the schema definition formats of struct and Union. As long as it is not a beginner, I believe there will be no problems in this regard .)
Struct is simply a set of correlated elements. It is a set. In fact, they are stored in a sequential order in the memory, and each element has its own memory space. So in what order? In fact, it is stored in the order of variables you declare. The following is an example:
Struct stest
{
Int A; // sizeof (INT) = 4
Char B; // sizeof (char) = 1
Shot C; // sizeof (shot) = 2
} X;
Therefore, the memory must occupy at least 4 + 1 + 2 = 7 bytes. However, the actual memory used is not 7 bytes, which involves the byte alignment mode. For more information, see the reprinted struct byte alignment analysis.
The difference between Union is that all its elements share the same memory unit and the memory size allocated to Union is determined by the largest element size of the type, the following memory is a double size:
Union Utest
{
Int A; // sizeof (INT) = 4
Double B; // sizeof (double) = 8
Char C; // sizeof (char) = 1
} X;
Therefore, the allocated memory size is 8 bytes.
Since it is Memory Sharing, naturally, it cannot store the values of multiple members at the same time, but can only store one value, that is, the value assigned to it, for example:
X. A = 3; X. B = 4.5; X. c = 'a ';
In this way, you can only see X. c = 'A', And the rest has been overwritten, which makes no sense.
Speaking of this, you should have understood the key difference between the two. It is nothing more than the allocation and use of memory units. However, there are still many tips to use struct and Union flexibly. For example, union can be used when the correlation of elements is not strong, thus saving the memory size; struct and union can also be nested with each other.
Difference between struct and Union