C StructuresLesson 41Free preview
C Struct Padding
This lesson is part of C · All levels
Summary
The compiler inserts byte padding between the struct members so that each member is at an address that aligns with their needs. As a result the size of a struct is often greater than the sum of the sizes of the entire member. Padding is important to understand when data is stored in a file, sent over a network, or used together by another programming language.
Key points
- Alignment means that a type is usually located at its own size multiple, e.g. int at a 4 byte multiple.
- Sizeof returns the struct size including all the padding, even the padding at the end so that the array elements stay in alignment.
- Member order affects size; group the same sized type to minimize padding.
- Pack can force assembly layouts, but can lower data access performance. (#pragma)
- For cross-platform data, serialize field per field, don't write raw struct directly to the file or network.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.