C memory alignment refers to the byte offset where data types must start. Structs have padding to align fields, and _Alignof queries alignment requirements. Proper alignment improves performance (cache lines, SIMD) and is required by hardware.
Use alignment awareness to understand struct layout, optimize for cache, and meet hardware requirements.
// compile: gcc -std=c11 -o alignment alignment.c // run: ./alignment // description: struct padding and alignment #include <stdio.h> #include <stdalign.h> struct Packed { char a; int b; char c; }; struct Optimized { int b; char a; char c; }; int main() { printf("Packed layout:\n"); printf(" size: %zu\n", sizeof(struct Packed)); printf(" alignof: %zu\n", alignof(struct Packed)); printf(" a offset: %zu\n", offsetof(struct Packed, a)); printf(" b offset: %zu\n", offsetof(struct Packed, b)); printf(" c offset: %zu\n", offsetof(struct Packed, c)); printf("Optimized layout:\n"); printf(" size: %zu\n", sizeof(struct Optimized)); printf(" alignof: %zu\n", alignof(struct Optimized)); return 0; }
Alignment requirements:
Padding:
Cache efficiency:
Hardware alignment:
_Alignof and alignas:
_Alignof(type): required alignment_Alignas(type): enforce alignment