c / intermediate
Snippet
Flexible Array Members in Structs
A flexible array member is a special array defined as the last member of a struct with no size. It allows the struct to act as a header for a variable-length memory block allocated on the heap.
snippet.c
c
1
2
3
4
5
6
7
8
#include <stdlib.h>struct Buffer {int capacity;char data[];};struct Buffer *b = malloc(sizeof(struct Buffer) + 1024);
Breakdown
1
char data[];
The flexible array member; it must be the last element.
2
malloc(sizeof(struct Buffer) + 1024);
Allocates space for the struct members plus 1024 bytes for the data array.