我是 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;
}
非常感谢。
最佳答案
您提供的是指针“树”而不是数组“树”。您必须为指针“tree”分配足够的内存,使其成为一个数组。您可以通过添加以下代码来完成此操作
tree=(Node*)malloc(size_of_array*sizeof(Node));
这将形成一个包含“size_of_array”个元素的数组。
还在 for 循环中声明 i,但我认为在分配内存后不需要循环。
关于c - 不会进入我的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41120653/