c and c++ struct definition declaration alignment parsing

  • 2020-06-03 07:48:18
  • OfStack

1. Definition/declaration mode

Type 1: Only structure names, no variables defined/declared


struct MyStruct
{
int i ; 
char a[10];
double b;
} ; 

Type 2: You have a structure name and declare a variable name


struct MyStruct
{
int i ; 
char a[10];
double b;
}structName ; 

or


struct MyStruct
{
int i ; 
char a[10];
double b;
} ; 

struct MyStruct structName;

// It can be defined simultaneously, e.g. struct MyStruct structName={7, "xxxxxxxxxx", 2.1};

// It can also be directly assigned between structures, such as struct MyStruct structName = structName1;

// The above is c style, c++ struct MyStruct structName.

Type 3: No structure name, declare variables directly (for this structure, you only need to declare 1 variable)


struct
{
int i ; 
char a[10];
double b;
}structName ; 

Type 4: With typedef


typedef struct MyStruct
{
int i ; 
char a[10];
double b;
}structName ; 

structName=struct MyStruct, structName is an alias for the structure type, not a variable.

You can have structName aa=struct MyStruct aa;

You can also do this:


typedef struct
{
int i ; 
char a[10];
double b;
}structName ; 

structName aa, same as above.

typedef is mainly for the convenience of the definition of c language structure variables always with the struct keyword, typedef after the use of c, c++ itself
The struct keyword is not needed, so it seems that it is not needed either.

2. Alignment

Such as:


struct MyStruct
{
double dda1;
char dda;
int type;
};
int i = sizeof(MyStruct);

According to vs2008 test i=16, "sizeof(MyStruct)=sizeof(double)+sizeof(char)+sizeof(int)=13" is wrong. This is a special treatment of variable storage by VC. To improve the storage speed of CPU, VC "allocates" the starting addresses of 1 variable. By default, VC specifies that the offset from the start address of each member variable to the start address of the structure must be a multiple of the number of bytes occupied by the type of the variable.

For the above example, 16=8+1+3+4, which is just a multiple of the number of byte boundaries of the structure (sizeof(double)=8), so there are no vacant bytes to fill.

So the size of the entire structure is: sizeof(MyStruct)=8+1+3+4=16, three bytes of which VC fills automatically without putting anything meaningful.

Such as:


structMyStruct
{
char dda;
double dda1;
int type;
};

sizeof (MyStruct) for 24 = 1 + 7 + 8 + 4 + 4; The 11 bytes are automatically filled by vc, and the last 4 is added to make the number of byte boundaries for the structure a multiple of the number of bytes for the type that takes up the most space in the structure.


Related articles: