Flexible Array Members and Anonymous Structs

Learn how to define variable-sized structures and use anonymous structs and unions to simplify nested data definitions.

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: