[C Language] number of bytes occupied by struct, storage and space allocation, and number of bytes
We all know that in the data type, char occupies 1 byte, short occupies 2 bytes, int occupies 4 bytes, and long occupies 8 bytes.
When calculating the size of a struct, you need to consider its memory layout. The structure is stored in units. The size of each unit depends on the size of the maximum basic type in the struct. Here are several examples:
1.
Struct{Char;Int B;Short c;} Str1;
Here, char occupies 1 byte, int occupies 4 bytes, and short occupies 2 bytes, which are stored in units, for example:
1 2 3 4
Because a occupies 1 byte, B cannot store, so open up a new unit to store B, and then open up a new unit to store c.
From this we can see that the struct is stored in the memory by unit, and the total number of bytes occupied is 3*4 = 12.
2.
Struct B{Char;Short c;Int B;} Str2;
Storage
1 2 3 4
Here, because B occupies 4 bytes, and a and c occupy 3 bytes in total, c is enough to store, so c is stored behind a, and then a new unit is opened to store B.
In this example, the number of bytes is 2*4 = 8.
3.
Struct c{Char;Char B [2];Char c [4];} Str3;
Storage
1 2 3 4 5 6 7
Because all data types are char, you do not have to open up new units and store a row.
The number of bytes occupied is 1*1 + 2*1 + 4*1 = 7.
To sum up, the struct is stored in the memory by unit. the maximum length of the opened unit depends on the Data Type that occupies the largest byte, in addition, we can find that the storage order has a certain impact on the space usage.
From the above three examples, we can see that the first one is the most space-consuming; the third is the most space-saving, but all uses the same type, and the Data Type generated by the field is lost, which is inconvenient to use; the second method is between the first and the third method, which is relatively compact in space and maintains the Data Type of fields in the struct. You can try to use sizeof () to learn more about the storage by cells in the struct.