Flexible array member

From Wikipedia, the free encyclopedia

C struct data types may end with a flexible array member[1] with no specified size:

typedef struct {
    size_t len; // there must be at least one other data member
    double arr[]; // the flexible array member must be last
    // The compiler may reserve extra padding space here, like it can between struct members
} DoubleArray;

Typically, such structures serve as the header in a larger, variable memory allocation:

// see section on size and padding
DoubleArray* darray = malloc(sizeof(DoubleArray) + ... * sizeof(double));
darray->len = ...;
for (int i = 0; i < darray->len; i++) {
    darray->arr[i] = ...; // transparently uses the right type (double)
}

Availability

References

Related Articles

Wikiwand AI