Reading this Skip List implementation I came across this code fragment:
typedef struct nodeStructure{
keyType key;
valueType value;
node forward[1]; /* variable sized array of forward pointers */
};
To me it seems that forward[1] denotes a one element array. And the comment calls it a variable sized array.
Do I misunderstand something or this is just a mistake in the source I’m reading?
This is a common trick for the older C compilers (before C99): compilers allowed you to dereference elements past the end of
forward‘s declared length when it is the last element of thestruct; you could thenmallocenough memory for the additionalnodeelements, like this:The trick lets you embed arrays of variable size in a structure without a separate dynamic allocation. An alternative solution would be to declare
node *forward, but then you’d need tomallocandfreeit separately from thenodeStructure, unnecessarily doubling the number ofmallocs and potentially increasing memory fragmentation:Here is how the above fragment would look without the hack:
EDIT (in response to comments by Adam Rosenfield): C99 lets you define arrays with no size, like this:
node forward[];This is called flexible array member, it is defined in the section 6.7.2.1.16 of the C99 standard.