我是C编程的初学者。我目前正在尝试使用数组实现特殊的树。 当执行我的代码时,它停止说:处理完成退出码11(分段故障)。出于某种原因,它在进入我的函数newTree之前停止。目前,我的程序所做的唯一事情是:它首先显示菜单,然后询问用户选择。之后,它会要求用户输入根名称和值。出于某种原因,它然后发展出分段故障。不会输入我的功能
这是我当前的代码:
//struct
typedef struct Tree {
char *name;
char *value;
_Bool isLeaf;
} Node;
//array
Node *tree;
//defining my functions
void newTree(Node n);
void add_child(Node n1, Node n2, int child_loc);
int main(void){
//menu
printf("The Tree Data Structure\n");
printf("Choose one of the following options: \n");
printf("1.Create a new tree consisting just of the root node n \n");
printf("2.Add a new child node to n \n");
printf("3.Prune \n");
printf("4.List Children \n");
printf("5.Traverse \n");
printf("6.Graft \n");
printf("7.Search \n");
printf("Option: ");
Node n, n1, n2;
//creating all nodes
for(int i=0; i<781; i++){
Node i = {(char*)malloc(sizeof(char)*16), (char*)malloc(sizeof(char)*80), 0};
}
int option;
scanf("%d", &option);
switch(option){
case 1:
printf("Enter root name: ");
scanf("%s", n.name);
printf("Enter root value: ");
scanf("%s", n.value);
//my problem
newTree(n);
break;
//other cases
default: printf("Incorrect option");
break;
}
return 0;
}
void newTree(Node n) {
strcpy(tree[0].name,n.name);
strcpy(tree[0].value,n.value);
int first_child_loc;
first_child_loc = 0;
//0 because first tree: tree[0]
first_child_loc = (0*5)+1;
if(strcmp("",tree[first_child_loc].name) == 0){
n.isLeaf = 1;
}else{
n.isLeaf = 0;
}
tree[0].isLeaf = n.isLeaf;
}
非常感谢你。
您可能对此讨论感兴趣(与您的问题没有直接关系)http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc。虽然我不能找到一个名为'createTree'的函数,我假设你的意思是'newTree'。我假设你的代码输出'Enter root value:'。更具体一点你的预期行为是什么以及实际行为是什么。 –
程序中的节点*树只是声明“树”作为指针。你将不得不分配内存给树,使其成为一个数组。另外,我不明白一件事,通过创建数组并存储值,不会使它成为树。树中每个节点之间必须有一些链接。 –