Data has to be properly aligned for decent efficiency, so the compiler is at liberty to add padding to the interior of a structure (anywhere except at the start).
Generally, an N-byte type (for 1, 2, 4, 8, 16 bytes) is aligned on an N-byte address boundary.
Therefore, for a 32-bit compilation, the structure has:
int id; // offset = 0, size = 4
char* name; // offset = 4, size = 4
char grade; // offset = 8, size = 1
char sex; // offset = 9, size = 1
double score; // offset = 16, size = 8
For a total size of 24. Note that even if you moved the double
around - say to the front of the structure, or to after the name, the size would still be 24 because all the elements of an array of the structure must be properly aligned, so there will be at least 6 bytes padding. (Sometimes, a double only needs to be aligned on a 4-byte boundary; the padding would then be 2 bytes instead of 6.)
Even without the double
member, the structure must be 12 bytes long so that the id
is properly aligned for the extra elements in an array - there would be 2 bytes of padding.
Some compilers provide programmers with a rope called #pragma pack
or thereabouts, and some programmers leap at the opportunity to hang themselves with the rope thus provided.