C flexible array members (FAM) allow a struct to have a variable-length array as its last member with size specified at runtime. Declare as type array[] with no size; allocate the struct plus extra space for array data.
Use FAM for variable-sized data structures without separate pointer indirection.
// compile: gcc -o fam fam.c // run: ./fam // description: flexible array members for variable-size structs #include <stdio.h> #include <stdlib.h> #include <string.h> struct Vector { int size; int capacity; int data[]; // Flexible array member }; struct Vector *create_vector(int capacity) { struct Vector *v = malloc(sizeof(struct Vector) + capacity * sizeof(int)); v->size = 0; v->capacity = capacity; return v; } void push(struct Vector *v, int value) { if (v->size < v->capacity) { v->data[v->size++] = value; } } int main() { struct Vector *v = create_vector(10); push(v, 1); push(v, 2); push(v, 3); printf("Vector size: %d\n", v->size); printf("Data: %d %d %d\n", v->data[0], v->data[1], v->data[2]); free(v); return 0; }
Declaration:
type array[] as last member, no size specifiedAllocation:
malloc(sizeof(struct) + n * sizeof(type))Advantages over separate pointer:
Limitations: