Why is c struct padding required in the __last__ element

I know the registration and its rules, why it is required, etc.

My question is asked struct,

struct my_struct {
   int a;
   char c;
};

      

In this case, the starting address c is word-aligned, but still the compiler adds 3 bytes (assuming 4 as the word size). no element after c and why do we need those 3 bytes? I have checked the following,

int g_int1;
struct my_struct st;
int g_int2;

      

above, I mean my other variable declarations are independent of the word alignment of the previous variable size. the compiler always tries to align the next variable regardless of its global or local automatic var.

I don't see any reason with the content as it is char and for one byte it doesn't matter. what is the reason, in my opinion, instead of checking the last compiler, the element condition always adds padding when required.

What is the real reason?

+3


source to share


3 answers


Because if sizeof(my_struct)

it was 5 and not 8, then if you did this:

my_struct array[2];

      



array[0]

will then be word-aligned, but array[1]

not. (Recall that an array lookup is done by adding multiples sizeof(array[0])

to the address of the first element.)

+9


source


Imagine you have an array struct my_struct

. How would its elements be line-aligned if they are not multiples of words in each size?



+6


source


So that the size of the object is also aligned. Imagine I have an array my_structs. In this case, you need to align the start address of each item. Therefore, sizeof (struct my_struct) must be "aligned". Otherwise, you won't be able to determine how much memory you need to allocate.

+1


source







All Articles