Structure alignment calculation

Transfer: https://blog.csdn.net/u011404495/article/details/54837797
Structure nesting calculation: https://blog.csdn.net/weixin_46028606/article/details/112602604?utm_medium=distribute.pc_relevant.none -task-blog-baidujs_baidulandingword-1&spm=1001.2101.3001.4242
Principle 1: The elements in the structure are placed in the memory one by one in the order of definition, but they are not closely arranged. Starting from the first address of the structure storage, when each element is placed in the memory, it will think that the memory is divided by its own size, so the location of the element must start at an integer multiple of its own width (in the structure The first address of the body variable is calculated as 0).
For example, in this example, first, the system will store the character variable a in the 0th byte (relative address, which refers to the first address of the memory development); then, when storing the integer variable b, it will store it in units of 4 bytes. Since the first four-byte module has data, it will be stored in the second four-byte module, that is, to 4~8 bytes; in the same way, when storing the double-precision real variable c, because of its The width is 8, when it is stored, it will be stored in units of 8 bytes, that is, it will find the first empty position that is an integer multiple of 8 and start storing. In this example, in this example, because of the first 8 word The section module is already occupied, so store c in the second 8-byte module. The overall storage diagram is shown in Figure 1.
Insert picture description here
Example 2:
struct X
{ char a; double b; int c; }S2;




In the second example, only the variable of the double type and the variable of the int type are interchanged. The test procedure remains the same, but the test result is completely different, sizeof(S2)=24, which is different from the 8+8+4=20 we calculated according to principle 1. This leads to our second principle.

Principle 2: After the first-principle analysis, check whether the calculated storage unit is an integer multiple of the length of the widest element among all elements. If it is, it ends; if it is not, fill in to its integer multiple.

In the second example, the storage length after the analysis is 20 bytes, which is not an integer multiple of the width of the widest element, so it is added to an integer multiple of 8, which is 24. Then there is no problem. The schematic diagram of its storage is shown in Figure 2.
Insert picture description here

Guess you like

Origin blog.csdn.net/chengcheng1024/article/details/115249787