简体   繁体   English

子代的多路树内存分配

[英]multiway tree memory allocation of children

I am trying to build a multi-way tree in C. I've got stuck on allocation memory for childrens. 我试图在C中建立多路树。我在分配给孩子的内存上遇到了麻烦。 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: 这是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. 按照我的逻辑,它应该可以工作。

I've found my error. 我发现了我的错误。 The memory allocation was ok. 内存分配还可以。 The problem was at adding new children. 问题在于增加了新的孩子。 I've added children for the current node instead of adding children to it's parent. 我为当前节点添加了子节点,而不是为其父节点添加子节点。

This was the solve: 这是解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM