Conditions (look at each of the basic types for a few bytes first):
voidSize_ () {printf ("char type:%d\n",sizeof(Char)); printf ("int type:%d\n",sizeof(int)); printf ("Float type:%d\n",sizeof(float)); printf ("Double type:%d\n",sizeof(Double)); return;}
Results:
First, how many bytes of memory does this struct occupy in memory?
struct mystruct{/ * structure 1*/int i_int ; Char C_char; Char s_char[9];} MyStruct;
What about this (exchanging data member order)?
struct mystruct{/ * Structural body 2*/char c_char ; int i_int; Char s_char[9];} MyStruct;
Now let it tell us.
intMain () {mystruct My_st= {0}; intSize_struct =sizeof(My_st); printf ("%d\n", (int) &my_st.i_int); printf ("%d\n", (int) &My_st.c_char); printf ("%d\n", (int) My_st.s_char); printf ("Memory Size:%d bytes \ n", size_struct); return 0;}
First look at the results of structure 1
As you can see: Int occupies 4 bytes and char occupies 1 bytes, then an array of type char has 11 bytes.
What the hell is this? Clearly defines a char array length of 9 why would it be 11
Don't worry, keep looking down.
View the results of struct 2 (not 16?) )
Haha, come out again a 20
answer to the announcement:
This is because the storage of the struct has a memory alignment mechanism, that is, the < struct size can be divisible by the widest base type member size >
The base type refers to a char int double, such that the alignment mechanism makes addressing more convenient
why struct 1 occupies 16 bytes :
Because a single char member is combined with its following array of char types, which is equivalent to an array of length 10 of a char type
Where the widest base type is int for 4 bytes and the subsequent "char[10]" array to satisfy is that int occupies 4 bytes of integer times the smallest is 12, so a total of 16 bytes
why struct 2 occupies 20 bytes :
The first member is a char single character, followed by an int type and cannot be combined to assign 4 bytes to a char
The subsequent char array will of course allocate 12 bytes, so 4+4+12=20 bytes
After understanding the alignment mechanism, we will analyze a
struct mystruct{/ * struct Body 3*/ char c_char; Double d_double; int i_int; Char s_char[9];} MyStruct;
Analysis :
The widest base type is a double that occupies 8 bytes----------------------------------------------------------------8
The first char occupies 1, but is padded to 8 bytes---------------------------------------------------------8
The following int occupies 4, which is equivalent to 4 char types, combined with the char array as "char[4+9]", to be padded with 16 bytes----16
Get Results-------------------------------------------------------------------------------------------32
Verify
That's how it is.
The end of this section ...
A study of the storage situation of C-language structure in memory------memory alignment