I know that different data type will allign. But I can't figure out why the size of this structure is 12.
#include <stdio.h>
struct ABC{
char a;
char b;
int k;
char c;
};
int main()
{
struct ABC a;
printf("%lu\n", sizeof(a)); //12
return 0;
}
CodePudding user response:
Ok it works like this
Here are the rules:
char
s are aligned to 1 byte
int
s are aligned to 4 bytes
The entirety of the struct must be aligned to a multiple of the largest element.
the final struct will be
struct ABC
{
char a; // Byte 0
char b; // Byte 1
char padding0[2]; // to align the int to 4 bytes
int k; // Byte 4
char c; // Byte 5
char padding1[3]; // align the structure to the multiple of largest element.
// largest element is int with 4 bytes, the closest multiple is 12, so pad 3 bytes more.
}