Data Structures in C: Memory Layout
C structs are more than just containers; they are precise mappings of memory. Understanding Padding and Alignment is crucial for performance and hardware communication.
Structure Padding
Compilers insert empty bytes (padding) between members to align data to word boundaries (e.g., 4 or 8 bytes) for faster CPU access.
c codestruct Padded { char a; // 1 byte // 3 bytes padding here int b; // 4 bytes char c; // 1 byte // 3 bytes padding here }; // Total size: 12 bytes! struct Optimized { int b; // 4 bytes char a; // 1 byte char c; // 1 byte // 2 bytes padding here }; // Total size: 8 bytes!
Unions: Space Efficiency
Unions allow multiple members to share the same memory location. Only one member can be used at a time. Ideal for variant types or low-level register mapping.
c codeunion Data { int i; float f; char str[16]; };
Creating a Linked List: The Industry Way
Always define your node structure and provide a clear API for interaction.
c codetypedef struct Node { void *data; // Generic pointer for flexibility struct Node *next; } Node_t; // Industry-level linked lists often use a 'Head' structure // to track metadata like length. typedef struct List { Node_t *head; size_t size; } List_t;
Bit-fields
For memory-constrained environments (like embedded kernels), bit-fields allow you to specify exactly how many bits a member should take.
c codestruct Flags { unsigned int is_ready : 1; unsigned int error_code : 3; };