C -多路树内存分配的孩子



我正试图在c中构建一个多路树。我已经为儿童分配内存。我有一个包含每个节点父节点的向量。下面是我的代码:

#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
}

NODE的结构如下:

typedef struct NODE {
    int info;                   
    int child_count;            
    struct NODE **children; 
} NODE;

我不确定问题是否在内存分配。按照我的逻辑,这应该行得通。

我发现我的错误了。内存分配正常。问题在于如何增加新的孩子。我为当前节点添加了子节点,而不是为它的父节点添加子节点。

结果如下:

void ADD_REF(int i) {
    v[t[i]]->children[v[t[i]]->child_count] = v[i];
    v[t[i]]->child_count++;
}

最新更新