I have a struct of the form:
typedef struct node {
unsigned int * keys;
unsigned int * branches;
} NODE;
The number of keys and branches is determined at runtime, but is known. It is derived from another struct:
typedef struct tree {
unsigned int num_keys_per_node;
} TREE;
In order to allocate a NODE for this TREE, the manual steps would be:
NODE node;
unsigned int keys[tree->num_keys_per_node];
unsigned int branches[tree->num_keys_per_node + 1];
node.keys = keys;
node.branches = branches;
I need to allocate a lot of these nodes inside tight loops, only temporarily as I traverse a data structure, discarding them quickly as the node traversal continues. I could write a function that returns a pointer and malloc() the keys and branches on the heap and free() them manually, but I’d prefer to use the stack if possible.
Since this initialization logic is going to be repeated in a number of places, how can I define a macro, so that I can effectively do something like:
NODE node = CREATE_NODE_FOR_TREE(tree);
I’m having difficultly seeing a way to do this which will result in the preprocessor giving a valid syntax.
Happy to hear other approaches to dynamic struct allocation on stack memory too.
EDIT | I should never need more than one node in memory at the same time, so I can re-use the one struct repeatedly too.
Try to pass
nodeas argument to the macro like so:This solution assumes at least c99.