pointers-memory · intermediate · ~15 min
Master struct alignment, member padding, and trailing structure padding calculations.
To maximize memory bus throughput, C compilers automatically insert padding bytes between struct members so that each field is aligned to a multiple of its natural alignment requirement.
Implement:
size_t compute_struct_size(const size_t *field_sizes, const size_t *field_aligns, size_t num_fields, size_t *offsets);
Compute the field offsets and total struct size according to standard C ABI struct alignment rules.
field_sizes == NULL, field_aligns == NULL, or num_fields == 0, return 0.current_offset = 0 and max_align = 1.i from 0 to num_fields - 1:current_offset up to the next multiple of field_aligns[i]: (current_offset + align - 1) & ~(align - 1).offsets != NULL, record offsets[i] = current_offset.current_offset += field_sizes[i].max_align = max(max_align, field_aligns[i]).current_offset up to the nearest multiple of max_align (struct trailing padding).field_sizes: array of byte sizes; field_aligns: array of alignments; num_fields: count; offsets: output array.
Returns total aligned struct size in bytes.
C11 freestanding struct layout arithmetic.
#include <stddef.h>
/* Compute member offsets and total struct size with internal and trailing padding.
Store offsets in offsets array (if non-NULL) and return total struct size. */
size_t compute_struct_size(const size_t *field_sizes, const size_t *field_aligns, size_t num_fields, size_t *offsets) {
(void)field_sizes; (void)field_aligns; (void)num_fields; (void)offsets;
return 0;
}
Forgetting trailing padding aligned to max_align; calculating alignment without bitwise masking.
Single field struct; already aligned fields; struct needing trailing padding for array stride.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.