I made a tree structure that only has a root. Then it’s up to the user to make nodes and either add them as children to the root or an other existing node. Here’s how the structure looks:
#define MAXCHILDREN 5 //max children a node can have
typedef struct node{
unsigned int id;
struct node* parent;
struct node* children[MAXCHILDREN];
}node;
typedef struct spantree{
node root;
}spantree;
Now what I want to achieve is to make say 4 nodes and add them as children to the root. Here is what I have done which doesn’t work properly:
for (i=0; i<4; i++){
node newNode;
newNode.id=i;
addChild(&newNode, &Root);
}
That doesn’t work as when I run
showChildId(0, &root); //where the first number denotes first child, second child etc.
showChildId(1, &root);
etc
I get the same id which mean that there is only one child added. So how do I go on making 4 different nodes and adding them to a parent(root in this case) in a loop?
This looks like homework to me so I’ll try to offer guidance rather than a definitive answer.
In this loop:
newNodeis created on the stack every iteration of the loop and it is only valid until the end of the iteration.To make it live longer you need to allocate some memory for it on the heap. Have a look at
malloc()andfree().