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 the struct
; you could then malloc
enough memory for the additional node
elements, like this:
nodeStructure *ptr = malloc(sizeof(nodeStructure)+4*sizeof(node));
for (int i = 0 ; i != 5 ; i++) { // The fifth element is part of the struct
ptr->forward[i] = ...
}
free(ptr);
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 to malloc
and free
it separately from the nodeStructure
, unnecessarily doubling the number of malloc
s and potentially increasing memory fragmentation:
Here is how the above fragment would look without the hack:
typedef struct nodeStructure{
keyType key;
valueType value;
node *forward;
};
nodeStructure *ptr = malloc(sizeof(nodeStructure));
ptr->forward = malloc(5*sizeof(node));
for (int i = 0 ; i != 5 ; i++) {
ptr->forward[i] = ...
}
free(ptr->forward);
free(ptr);
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.