The compiling environment is vc6.0.
Summary of memory alignment in sizeof (struct:
First, find the type of the largest byte occupied by the entire struct. Assume that the number of bytes occupied by the struct is m, and then add them in the declared order to obtain the number of bytes M. If the total number of bytes of M is less than m, next, let's look at the next byte n. If m + n> m, then n is not calculated, and m is changed to m first, and then calculated from N. (The statement may not be clear enough. Let's look at the example)
(1) first definition method
Struct {
Int;
Char C;
Double B;
};
The result of calling sizeof (a) is 16.
The maximum number of bytes is 8 bytes.
Int type occupies 4 bytes, M = 4, m <8
Char occupies 1 byte, 4 + 1 = 5 <8
The double type occupies 8 bytes, 5 + 8> 8;
Therefore, the five bytes are first aligned to eight bytes.
Then let's look at double, 8 + 8 = 16 bytes.
(2) method 2
Struct B
{
Int;
Char C;
Int D;
Double B;
};
The result of calling sizeof (B) is 24.
Int type occupies 4 bytes, M = 4 <8
Char type, M = 5 <8
Int type, m + n> 8,
Therefore, the first five bytes are first aligned to 8,
Let's look at the int type, which is 4
Double is 8, 4 + 8> 8
Therefore, the memory alignment of 4 bytes is changed to 8 bytes.
Double type, 8 bytes. 8 + 8 + 8 = 24.
(3) third definition method
Struct C
{
Int;
Char C;
Char D;
Double B;
};
The result of sizeof call is 16.
4 <8
4 + 1 <8
4 + 1 + 1 <8
4 + 1 + 1 + 8> 8 + 4 + 1 + 1 = 8
8 + 8 = 16.
(4) fourth definition method
Struct d {
Int;
Double B;
Char C;
};
The result of sizeof call is 24.
4 <8
4 + 8> 8
4 = 8, 8 = 8
1 <8 1 = 8
8 + 8 + 8 = 24.
Welcome to shoot bricks.