Site Tools


c-flexible-array-members

Table of Contents

C flexible array members

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.

Example

// 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;
}

Common patterns

Declaration:

  • type array[] as last member, no size specified
  • Only valid as last member (C99)

Allocation:

  • malloc(sizeof(struct) + n * sizeof(type))
  • Extra space allocated for array elements
  • All in one contiguous allocation

Advantages over separate pointer:

  • Single allocation, better cache locality
  • No extra pointer dereferencing
  • Cleaner semantics for fixed-size arrays

Limitations:

  • Must be last member
  • Can't be nested in other structs
  • Requires careful size calculation
c-flexible-array-members.md · Last modified: