Union: Common body
struct: struct
The difference between the two:
1: Both the common body and the struct are composed of a number of different data type members, but at any one time, the common body only holds a selected member, and the struct holds all the member variables.
2: For the different members of the common body assignment, will be overridden for the other members, the original member value will not exist, and for the structure of the different members of the assignment is not affected
3: Different memory allocations
The size of the Union is the maximum of all variables within it, and the size is allocated in multiples of the maximum type
Such as:
typedef Union
{
Char c[10];
Char cc1;
}u11;
typedef Union
{
Char c[10];
int i;
}u22;
typedef Union
{
Char c[10];
Double D;
}u33;
sizeof (U11) results
sizeof (U22) results in a space allocation according to sizeof (int)
sizeof (U33) results are based on sizeof (double) * * allocation of space.
struct structs are similar in that they are allocated in multiples of the maximum type , but are also related to the order
Such as:
typedef struct S1
{
char c;
Double D;
}S11;
typedef struct S2
{
char c;
Char cc;
Double D;
}S22;
typedef struct S3
{
char c;
Double D;
Char cc;
}s33;
sizeof (S11) result should be 9, but the system is allocated according to sizeof (double) , so the size is
sizeof (S22)The result is that it should beTen, but the system followssizeof (DOUBLE) * *allocated, so the size is -, first assign8bytes toC,Ctakes one byte, the remaining7bytes can be storedcc, so the system has no additionalccallocates memory. ccafter having the memory remaining6bytes cannot be storedD, the system is an additionalDDistribution8bytes, the entire allocation wasted memory6bytes.
sizeof (S22)The result is that it should beTen, but the system followssizeof (double)allocated, so the size is -because it is related to the order of definition, so when givingCDistribution8bytes, the remaining7bytes cannot be storedD, so the system is again assigned8bytes toD, and then assign8a self-givenccand wasted after allocating -bytes of space. So, in defining the structure of the bodystructthe time to followS33in order to save memory.
Detailed differences between Struct and Union