Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How many bytes does int occupy in the structure variable?
How many bytes does int occupy in the structure variable?

? How many bytes does int occupy in the structure variable? Memory alignment issues need to be considered.

?

Reasons for memory alignment:

1) Some platforms can only access specific types of data at specific addresses;

< p> 2) Improve the speed of data access. For example, some platforms read data from even addresses every time. For an int type variable, if it is stored from an even address unit, it only takes one read cycle to read the variable; but if it is stored from an odd address If stored in the unit, it takes 2 read cycles to read the variable. ? Let’s use an example to illustrate the alignment:

Example 1, char, int alignment; #include?

struct?node

{ char?a; int?b;

};

int?main()

{ struct?node?QING; printf("%d\ n",sizeof(QING)); return?0;

}

Output result: 8 ?

Explanation: In the structure (note the variable definition order), char is 1 byte, int is 4 bytes, structure byte alignment: char and int are aligned. So pad the char to 4 bytes.

So the bytes occupied by the final structure are: 4 + 4 = 8;

Example 2, char *, int alignment; #include?

struct?node

{ char?a[5]; int?b;

};

int?main()

{ struct?node?QING; printf("%d\n",sizeof(QING)); return?0;

}

Output result: 12 ?< /p>

Explanation: The char a[4] in the structure has been aligned with the int below, but there is still a char a[1] left, which also needs to be completed to int (4).

So the final result: 8 + 4 = 12

Example 3, char, int, double alignment; #include?

struct? node

{ char?a; int?b; double?c;

};

int?main()

{ struct?node?QING; printf("%d\n",sizeof(QING)); return?0;

}

Output result: 16?

< p>Explanation: The two bytes of char and int in the structure (whole) are aligned with the double below. Therefore, the total number of bytes of char and int must be 8.

So the final result: 8 + 8 = 16

Example 4, char, double, int alignment; #include?

struct? node

{ char?a; double?c; int?b;

};

int?main()

{ struct?node?QING; printf("%d\n",sizeof(QING)); return?0;

}

Output result: 24?

< p>Explanation: Comparing Example 3, we found that only the order of definitions in the structure was changed, but the results were different. So why is this? In fact, it is like this. The char above must be aligned with the double, so the char

bytes must be completed to double (8), and then the double cannot be aligned with the int below, right? Because double is inherently larger than int, it is impossible to align. Then only int and

double are aligned, so int must also be completed to double (8).

So the final result is: 8 + 8 + 8 = 24

So the bytes occupied by the int type variable in the structure depends on the specific structure.

The above code was tested in win7_64bit?Devcpp 5.5.3 environment.