【发布时间】:2015-05-21 06:15:33
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
struct node{
char *word;
int depth, children;
struct node **child;
};
typedef struct node node;
node *createTree();
node *createNode(char *word,int depth);
int main(int argv,char *argc[]){
node *root,*current_node;
root=createNode("root",0);
char *array[]={"string1","string2","string3"};
current_node=root;
printf("root has been created with word: %s \n",current_node->word);
int i;
for (i=0; i<3; i++){
current_node->child[i]=createNode(array[i],(current_node->depth)+1);
current_node->children++;
printf("%s has been inserted to the tree\n",current_node->word);
}
}
node *createTree(){
printf("root has been created\n");
return createNode("",0); /*creates the first node*/
}
node *createNode(char *word,int depth){
node *new_node;
new_node=malloc(sizeof(node));
new_node->word=word;
new_node->depth=depth;
new_node->children=0;
new_node->child=NULL;
}
所以我在这里要做的是构建一个 n 叉树。我使用 createNode 函数来创建根的子节点,但是一旦我尝试将新节点的地址链接到子节点,程序就会因分段错误而崩溃。我知道我的错误可能是,我试图创造孩子的方式,但我找不到。帮助任何人?
【问题讨论】:
-
创建节点时,
child指针被设置为NULL。但是您的for循环试图引用child[i],所以这是一个分段错误。您需要为child节点指针数组分配内存,然后才能引用它们。