The struct contains different data types, and the data structure types occupy space. For example, the char type occupies 1 byte, and the short int type occupies 2 bytes, int, long int, pointer, float occupy 4 bytes, and double occupies 8 bytes (in windows and linux ). However, the computer system limits the allowed addresses of basic data types, A certain type of object must be a multiple of 2, 4, or 8 (to simplify the hardware design between the processor and the storage system-you can save at least one address line ).
How can we determine the space occupied by a given struct data?
Very easy! We can make correct judgments based on alignment principles. But remember: it is not the number of bytes of the variable that occupies the largest space in the struct as mentioned in some tutorials, multiplied by the total number of variables, or the total space occupied by all variables, then fill in the multiples of the number of bytes occupied by the largest space variable.
So how can we calculate it?
The following is an example:
Struct
{
Int I;
Char j;
Int k;
Char r;
Int s;
} S;
Sizeof s =?
The answer is 20.
Struct
{
Int I;
Char j;
Char r;
Int k;
Int s;
} S;
Sizeof s =?
The answer is 16.
Struct
{
Double I;
Char j;
Char r;
Int k;
Int s;
} S;
Sizeof s =?
The answer is 20.
Struct
{
Double I;
Char j;
Int k;
Char r;
Int s;
} S;
Sizeof s =?
The answer is 24.
Struct
{
Double I;
Char j;
Short k;
Char r;
Short s;
} S;
Sizeof s =?
The answer is 16.
Can you see the problem? The computer system is aligned according to the maximum number of bytes occupied by space in variable types except double in struct. Therefore, the above results are available. Note that when char is isolated from int variables, one char also occupies 4 bytes, however, when two or even four char strings are stored next to each other, they only occupy 4 bytes (the char variable is accessed in multiples of 1. In this case, the address line between the CPU and memory cannot be reduced, because it is possible to access an address, and the last bit is also 1 ).