Вопрос

    struct struct_name {
                        char a;
                        char b;
                        char c;
     }

The size of the structure struct_name is 3 but

   struct struct_name1 {
   char a;
   char b;
   char c;
   int d;
   char e;
   char f;
   char g;
};

the size of struct_name1 is 12 why? I know this is because of padding but why the size of structure stuct_name is 3 and why the sizeof structure struct_name1 is not 11.

Это было полезно?

Решение

This all depends on the plaform, but assuming a relatively normal environment with 32bit ints that need to be aligned on 32bit boundaries, you need that structure to be a multiple for 4 bytes in size. Otherwise, if you try to make an array of struct_name1, the int in the middle won't be aligned properly (there cannot be padding in between elements in an array).

If the compiler set that struct to 11, and array of two of these would look like:

abcXddddefgabcXddddefg  // X is padding
0   4   8   C  F        // hex offset

You see the first byte of the second int d is at offset 0x0F wich is 15 - not 4-byte aligned. So an extra char of padding is added:

abcXddddefgXabcXddddefgX  // X is padding
0   4   8   C   0   4     // hex offset

and the middle int will always have the correct alignment.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top