Sun Studio 12: C User's Guide

D.1.8 Flexible Array Members

6.7.2.1 Structure and union specifiers

Also known as the “struct hack”. Allows the last member of a struct to be an array of zero length, such as int foo[]; Such a struct is commonly used as the header to access malloced memory.

For example, in this structure, struct s { int n; double d[]; } S;, the array, d, is an incomplete array type. The C compiler does not count any memory offset for this member of S. In other words, sizeof(struct s) is the same as the offset of S.n.

d can be used like any, ordinary, array-member. S.d[10] = 0;.

Without the C compiler’s support for an incomplete array type, you would define and declare a structure as the following example, called DynamicDouble, shows:


typedef struct { int n; double d[1]; ) DynamicDouble;

Note that the array d is not an incomplete array type and is declared with one member.

Next, you declare a pointer dd and allocate memory thus:


DynamicDouble *dd = malloc(sizeof(DynamicDouble)+(actual_size-1)*sizeof(double));

You then store the size of the offset in S.n thus:


dd->n = actual_size;

Because the compiler supports incomplete array types, you can achieve the same result without declaring the array with one member:


typedef struct { int n; double d[]; } DynamicDouble;

You now declare a pointer dd and allocate memory as before, except that it is no longer necessary to subtract one from actual_size:


DynamicDouble *dd = malloc (sizeof(DynamicDouble) + (actual_size)*sizeof(double));

The offset is stored, as before, in S.n thus:


dd->n = actual_size;