Flexible array members in C99
What you'll learn: How to create structures that can hold a variable amount of data at the end of their memory layout without using pointers.
The problem with fixed sizes
Imagine you are building a digital "shipping crate" (a struct). Inside, you have a label (header data) and the items themselves. In standard C, if you define int items[10], your crate is always exactly big enough for 10 items. If you only have two items, you waste space; if you have eleven, the crate breaks.
While you could use a pointer like int *items, this forces the actual data to live somewhere else in memory, requiring two separate allocations and causing the CPU to jump around to find your data.
The "Open-Ended" Struct
C99 introduced Flexible Array Members. By declaring an array with empty brackets [] as the very last member of a struct, you tell the compiler: "This struct has a fixed header, but I will decide how much extra space to tack onto the end at runtime."
The struct itself doesn't allocate any space for the flexible member. Instead, you calculate the total size you need (header + data) and allocate it all at once using malloc.
Implementation Example
Here is how you define and use a structure that can hold any number of integers:
#include <stdio.h>
#include <stdlib.h>
struct DataBatch {
int batch_id;
int count;
// Flexible array member: must be the last element
int values[];
};
int main() {
int num_elements = 5;
// Calculate size: size of the struct + (number of elements * size of each element)
size_t total_size = sizeof(struct DataBatch) + (num_elements * sizeof(int));
// Allocate the struct and the array as one continuous block
struct DataBatch *my_batch = malloc(total_size);
if (my_batch != NULL) {
my_batch->batch_id = 101;
my_batch->count = num_elements;
// You can now use 'values' like a normal array
for (int i = 0; i < num_elements; i++) {
my_batch->values[i] = i * 10;
}
free(my_batch);
}
return 0;
}
Why use this pattern?
By using a flexible array member, all your data is contiguous (touching in memory). This is much faster for the computer to read than following a pointer to a different location. It also simplifies memory management: you only have to malloc once and free once to handle both the header and the data.
Key takeaway
A flexible array member (type name[]) must be the last element in a struct and allows you to allocate a single, continuous block of memory for both a header and a variable-length payload.