I have some structs for which i am checking their sizes. According to the rules of padding, i am expecting different results. When i have a char of size between 4 and 8, i see that padding is applied to the char up to size 8, but padding is not applied for the preceding integer or for the last integer/variable of the struct.
The main question here is why padding is not applied to integers whenever they are followed by char of size bigger than 4?
What is the meaning of applying padding to the char to reach 8 bytes, if integer still use 4 bytes?
Below, you can see the code why my questions in comments:
#include <stdio.h>
typedef struct {
int i;
char str[3]; //padding of 1
int f;
} stru_10;
//size is 4+4+4 = 12
typedef struct {
int i; //why no padding applied here?
char str[7]; // padding of one
int f; //why no padding applied here?
} stru_11;
//Actual result : size is 16. Why no padding on integers?
typedef struct {
int i; //why no padding applied here?
char str[9]; // padding of 3
int f; //why no padding applied here?
} stru_12;
//Actual result : Size is 20. Why no padding on integers?
typedef struct {
int i; //why no padding applied here?
char str[5]; // padding of 3
int f; //why no padding applied here?
} stru_13;
//Actual result : Size is 16. Why no padding on integers?
typedef struct {
int i;
char c; // padding of 3
int f;
} stru_14;
//Actual result. Size is 12 as expected.
typedef struct {
int i; // padding of 4
char *c; // padding of 3
int f; //padding of 4
} stru_15;
//Actual result. Size is 24 as expected(8*3).
int main(void) {
printf("Size of stru_10 is %d\n",sizeof(stru_10)); //12
printf("Size of stru_11 is %d\n",sizeof(stru_11)); //16
printf("Size of stru_12 is %d\n",sizeof(stru_12)); //20
printf("Size of stru_13 is %d\n",sizeof(stru_13)); //16
printf("Size of stru_14 is %d\n",sizeof(stru_14)); //12
printf("Size of stru_15 is %d\n",sizeof(stru_15)); //24
return 0;
}