This is a common trick for older C compilers (prior to C99): the compilers allowed you to cast elements at the end of the forward declared length when this is the last element of the struct ; you could malloc get enough memory for additional node elements, for example:
nodeStructure *ptr = malloc(sizeof(nodeStructure)+4*sizeof(node)); for (int i = 0 ; i != 5 ; i++) {
The trick allows you to embed arrays with a variable size in the structure without separate dynamic allocation. An alternative solution would be to declare node *forward , but then you would need malloc and free separately from nodeStructure , without having to double the number of malloc and potentially increase memory fragmentation:
Here is what this fragment would look like without hacking:
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 Adam Rosenfield's comments): C99 allows you to define arrays without size, for example: node forward[]; This is called a flexible member of the array; it is defined in section 6.7.2.1.16 of the C99 standard.
source share