For performance or hardware reasons, fields in structures should be suitably aligned. Read about data structure alignment (details depend upon the target processor and the ABI).
In your example on x86-64/Linux:
struct student {
char name;
int age;
float weight;
};
the field name
has no alignment requirement.
the field age
needs 4 bytes aligned to a multiple of 4
the field weight
needs 4 bytes aligned to a multiple of 4
so the overall struct student
needs 12 bytes aligned to a multiple of 4
If weight
was declared double
it would need 8 bytes aligned to a multiple of 8, and the entire structure would need 16 bytes aligned to 8.
BTW, the type of your name
field is wrong. Usually names are more than one single char. (My family name needs 13 letters + the terminating null byte, i.e. 14 bytes). Probably you should declare it a pointer char *name;
(8 bytes aligned to 8) or an array e.g. char name[16];
(16 bytes aligned to 1 byte).
The GCC compiler provides a nice extension: __alignof__
and relevant type attributes.
If performance or size is important to you, you should put fields in struct
in order of decreasing alignment requirements (so usually start with the double
fields, then long
and pointers, etc...)