I don't know where you get the idea about char
or int
being calculated as "8 bytes". No, every type is calculated in accordance with its size: char
as 1, int
as 4 on a 32-bit platform (not 8, but 4). Alignment requirements for each type are normally the same as its size.
For this reason, when the structure contains the members of the same type, the total size of that structure will normally be the exact sum of the sizes of its members: a structure of 3 char
s will have size 3, and the structure of two int
s will have size 8.
Apparently type short
on your platform has size 2, so, expectedly, a structure of 3 shorts has size 6, which is exactly what you observe.
However, when your structure contains members of different types, then the difference between alignment requirements of different types comes into play. If the alignment requirement of the next field is stricter than the alignment requirement of the previous field, the compiler might have to add some padding bytes between these fields (to properly align the next member), which will affect the final size of the struct. Also, the compiler might have to add some extra padding bytes after the last member of the structure to satisfy alignment requirements in an array.
For example, a structure that looks as follows
struct S {
char c;
int i;
};
will most likely occupy 8 bytes on your platform because of the need for 3 padding bytes after the char
member. Note, char
counts as 1, int
as 4 and the extra 3 padding bytes between them make it 8.
Note also that this might easily introduce the dependency of the final size of the structure on the order in which the members are declared. For example, this structure
struct S1 {
char c1;
int i;
char c2;
};
on your platform will probably have size 12, while this one
struct S2 {
int i;
char c1;
char c2;
};
will occupy only 8 bytes. This last example is intended to illustrate that the final size of the structure cannot be expressed in terms of how many bytes each member "counts" for. The relationships between the members are also important.