I am trying to build a multi-way tree in C. I've got stuck on allocation memory for childrens. I have a vector which contains the fathers of each node. Here is my code:
#define MAX_CHILDS 10
int t[10] = {1, 2, 4, 1, -1, 3, 2, 1, 0, 4};
NODE *root;
NODE *v[MAX_CHILDS];
//add children for specified node
void ADD_REF(int i) {
v[i]->children[v[i]->child_count] = v[t[i]];
v[i]->child_count++;
}
//creates the tree
NODE *T1(int n, int *t) {
int root = 0;
for (int i = 0; i < n; i++) {
v[i] = (NODE *) malloc(sizeof(NODE));
v[i]->info = i;
v[i]->child_count = 0;
v[i]->children = (NODE **) malloc(sizeof(NODE)); // I think the problem is here
}
for (int i = 0; i<n; i++) {
if (t[i] == -1)
root = i;
else
ADD_REF(i);
}
return v[root];
}
void main() {
root = T1(MAX_CHILDS, t);
print_tree(root, 0); // prints the tree
}
Here is the structure of the NODE:
typedef struct NODE {
int info;
int child_count;
struct NODE **children;
} NODE;
I am not sure exactly if the problem is at the memory allocation. With my logic it should work.