How to align the structure struct in C language
This article mainly introduces "how to align the structure struct in C language". In the daily operation, I believe that many people have doubts about how to align the structure struct in C language. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to align structure struct in C language". Next, please follow the editor to study!
Struct, a collection of interrelated elements, each element has its own memory space; each element is stored in memory in order, that is, the order in which it is defined; the total memory size occupied by a struct is not the sum of the space occupied by each element, but the problem of byte alignment.
The offset of each element in struct relative to the first address of the structure is divisible by the size of that element (for some compilers, if the size of the element is greater than 4, the offset can be divisible by 4).
Test the code:
[xdb@localhost test] $cat test.cpp#include # include using namespace std;#define LL long long struct E1 {int a; char b; char c;} e1 struct E2 {char b; int a; char c;} e2struct E3 {char a; short b; int c; LL d;} e3 struct E4 {int c; LL d; char a; short b;} e4itstruct E5 {char A1 recrimina 3liao a4rect a5fora6;} e5scapstruct E6 {char A1 } e6 struct E7 {struct E5 elem5; struct E6 elem6; LL a;} e7 puts struct E8 {char a [9];} e8 puts struct E9 {struct E8 elem8; LL a;} e9 puts struct E10 {char a;}; int main () {puts ("- > E1"); cout