I recently reviewed the C language and felt that my previous learning and understanding of C was actually shit. Today, I am looking at the data alignment issue concerning the storage and allocation of members in the struct. I would like to share it with you. I just want to summarize it.
There are two types of Data Alignment: natural alignment and forced alignment. 1. Check the natural alignment first. The following procedures are available:
#include <stdio.h>
typedef struct
{
char c1;
long l;
char c2;
double d;
}a;
typedef struct
{
char c1;
char c2;
long l;
double d;
}b;
int main()
{
printf("%d,%d\n",sizeof(a),sizeof(b));
return 0;
}
The output is as follows:
The analysis is as follows: the member variables of the two struct are identical, but the order is different. After data alignment, the struct occupies different spaces. Structure A is in the following State after being naturally aligned:
C1 occupies one byte for the char type, and then needs to fill 3 bytes for the natural alignment of L. L is long type, occupies 4 bytes, C2 IS char type, in order to make the double precision D alignment, you need to add 7 bytes in C2, then D occupies 8 bytes. The result is: 1 + 3 + 4 + 1 + 7 + 8 = 24. According to the same rules, the space occupied by struct B is 16.
The natural alignment rules can also be summarized as follows: the offset of the address that each member variable stores to the starting address of the structure is sizeof (type) or an integer multiple of it. The total size of a structure is an integer multiple of the largest sizeof type in its members. Therefore, when defining a struct, it is best to declare the variables in the structure according to the type size from small to large to reduce the space filled in the middle.
2. For forced alignment, use # pragma pack (n) to set the alignment coefficient.
#pragma pack(4)
typedef struct
{
char c1;
long l;
char c2;
double d;
}a;
#pragma pack()
The output is as follows. The size of a is changed to 20.
Set n = 8
#pragma pack(8)
typedef struct
{
char c1;
long l;
char c2;
double d;
}a;
#pragma pack()
The size of the type is the same as that of the natural alignment. The result is 24.
Because # pragma pack (n) is used to set the alignment coefficient in two cases: first, if n is greater than or equal to the number of bytes occupied by the member, the offset must meet the default alignment mode, that is, the natural alignment mode. 2. If n is less than the number of bytes occupied by the member type, the offset is a multiple of N, and the default alignment mode is not required. The total size of the structure also has a constraint, which is divided into the following two cases: if n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be a multiple of the space occupied by the largest variable;
Otherwise, it must be a multiple of N.
That one *, street shot, gangbaochang ~
[References] "programmer's career success 」