Learn C
#include "structstypes/flexible_arrays.h"

Flexible Array Members in C

#concept

A flexible array member (C99) ends a struct with an unsized array — struct Buf { size_t len; char data[]; }; — letting one allocation hold header plus payload contiguously: malloc(sizeof(struct Buf) + n). The struct itself contributes no storage for the member (sizeof ignores it), and the trailing array indexes exactly like a normal one.

This replaces the old struct-hack (char data[1] with over-allocation) with defined behavior, powering network packets, variable records, and string builders. Rules: last member only, no arrays of such structs, and always allocate header-plus-payload together.

#how it works
1

Unsized trailing array

char data[]; as the final member claims no storage itself — the struct is a header awaiting its payload.

2

Allocate together

malloc(sizeof(struct Buf) + n) reserves header plus n payload bytes in one block — one allocation, one free.

3

Index normally

b->data[i] works like any array within the allocated span — bounds are your documented contract.

4

Replaces the struct hack

Old char data[1] over-allocation was undefined behavior that happened to work; flexible members are the defined version.

#example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
struct Msg {
int id;
char text[];
};
 
int main(void) {
struct Msg *m = malloc(sizeof *m + 6);
if (!m) return 1;
m->id = 7;
memcpy(m->text, "hello", 6);
printf("%d %s\n", m->id, m->text);
free(m);
return 0;
}
Output
7 hello
1One allocation covers the header plus six payload bytes (hello plus terminator).
2Header field and flexible payload fill independently through the same pointer.
3Single free releases both — header and payload share one lifetime by construction.
#use cases
Network packets: fixed header plus variable body in one allocation
Variable-length records in file formats and databases
String builders growing payload with header metadata attached
Replacing legacy [1]-sized struct hacks with defined behavior

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.