【发布时间】:2014-05-14 17:24:26
【问题描述】:
我正在尝试在 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;
我不确定问题是否出在内存分配上。按照我的逻辑,它应该可以工作。
【问题讨论】:
-
真正的问题是什么?
-
我不知道如何为节点向量动态分配内存,因为我不知道有多少节点。
-
为什么不呢?
info&child_count是整数,children只是一个指针。 -
我是 C 新手,但我注意到了两件事。每个节点都有一个指针。因此它会表现得像一个链表而不是多路树。其次,你为什么使用两个*。你不应该只用一个吗?
-
2x* 表示 NODE 类型的向量
标签: c algorithm multiway-tree