Flexible Array Members and Anonymous Structs
Explore the use of flexible array members introduced in C99 to handle variable-sized data within structures and how anonymous structs and unions in C11 simplify nested member access. Understand memory allocation requirements and practical applications to write efficient, flexible C programs.
We'll cover the following...
As studied earlier, C structures are traditionally fixed-size. This works well for many programs, but it becomes limiting when a structure must contain data whose length is only known at runtime.
C99 and C11 introduced two structure-related features that address this limitation in different ways:
Flexible array members (C99) allow the last member in a structure to represent a variable-length array whose actual size is determined during allocation.
Anonymous structs and unions (C11) allow nested structures or unions to be defined without assigning them a separate name, making member access simpler and more direct.
Flexible array members
Many real-world data structures have a shape. They include a fixed-size header (metadata) and a variable-sized payload. For example, a message may contain a length field and a character buffer of that length.
A common approach is to store a fixed array inside the structure:
struct Message {int length;char data[10];};
This structure always reserves space for exactly ten characters. Even if you only use three characters, the remaining seven bytes are still allocated. More importantly, the size cannot change at runtime.
To support variable-sized data, C99 allows declaring a flexible array inside a structure. A flexible array member is ...