I have a node with this structure:
struct node
{
unsigned long key;
unsigned long value;
struct node* lChild;
struct node* rChild;
};
I have a dummy node which has default values:
struct node* newSpecialNode()
{
struct node* node = (struct node*) malloc(sizeof(struct node));
node->key = 0;
node->value = 0;
node->lChild = NULL;
node->rChild = NULL;
return(node);
}
All nodes in my data structure will call this method to create a node.
struct node* newInternalNode(unsigned long key, unsigned long value)
{
struct node* node = (struct node*) malloc(sizeof(struct node));
node->key = key;
node->value = value;
node->lChild = newSpecialNode();
node->rChild = newSpecialNode();
return(node);
}
I call the function newSpecialNode()
for left and right child.
So there are two malloc
calls. But whenever I create a node, I always create two dummy nodes.
So I wanted to do a single malloc which allocates memory for both lChild
and rChild
.
Possibly allocate a double word and reference its parts. But I do not know how to do it.
I tried this approach. But again I need to do two mallocs.
struct node** ptrToTwoNodes = (struct node**) malloc(2*sizeof(struct node*));
ptrToTwoNodes[0] = (struct node*) malloc(sizeof(struct node));
ptrToTwoNodes[1] = (struct node*) malloc(sizeof(struct node));