I have read that characters are a special case, they are equally expensive from anywhere they live inside a single machine word, hence they don't have preferred alignment.
According to the above statement the size of both Struct_1
and Struct_2
should be 5 bytes. The Struct_1
is occupying 5 bytes as per the expectation but the Struct_2
is occupying 8 bytes.
Please explain me the reason behind this.
Going further I have printed the address of the individual members inside the Struct_2
. It confirms that padding space is being added after the last member char g
.
Why is padding required at the end of the last member?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Struct_1 {
char a;
char b;
char c;
char d;
char e;
} Struct_1;
typedef struct Struct_2 {
int f;
char g;
} Struct_2;
int main(void) {
Struct_2 strc2;
printf("\tsizeof(Struct_1): %ld\n", sizeof(Struct_1));
printf("\tsizeof(Struct_2): %ld\n", sizeof(Struct_2));
printf("\tsizeof(strc2.f) : %ld\n\n", sizeof(strc2.f));
printf("\t&(strc2.f) = %p\n", &(strc2.f));
printf("\t&(strc2.g) = %p\n", &(strc2.g));
return (0);
}
Output of the above code:
sizeof(Struct_1): 5
sizeof(Struct_2): 8
sizeof(strc2.f) : 4
&(strc2.f) = 0x7ffe07b08c50
&(strc2.g) = 0x7ffe07b08c54