【发布时间】:2013-02-14 01:41:06
【问题描述】:
编辑:开关的默认值是“无效选项”,我只是想创建一个树而已,程序正在编译,当我选择创建树的选项时,它只是说分段错误
这几天我一直在做简单的数据结构程序,分段错误是我最困扰的一个,我在互联网上研究了这个错误并得到了这个link,实际上并没有帮助。
我正在尝试创建一个二叉搜索树。并且 create 的返回类型不是 void,它是 struct tree *
程序:
struct tree{
int data;
struct tree *rchild, *lchild;
};
struct tree * create(struct tree * root, int d){
if(root==NULL) {
root = (struct tree *) malloc(sizeof(struct tree));
root->data=d;
root->rchild=NULL;
root->lchild=NULL;
}else if(root->data < d) create(root->rchild, d);
else if(root->data > d) create(root->lchild, d);
else if(root->data == d) printf("duplication error");
}
main(){
struct tree *root;
int choice, c;
while(choice!=5){
printf("Enter choice\n1-insert into tree\n5-exit");
scanf("%d", &choice);
switch(choice){
case 1:
printf("enter data to be inserted");
scanf("%d",&c);
printf("error after scanf ");
create(root,c);
break;
case 5: exit(0); default: printf("invalid option");
}
}
}
我使用的操作系统是 Backtrack 5 R1
给给-1的人:先生,如果我的问题如此愚蠢和没有建设性,请告诉我的答案
有一个类似的linked list question,这个问题我也回答过,顺便写个树程序。
【问题讨论】:
-
其实你可以运行这个c程序,当我在gcc中运行它时它正在编译,当我执行它时它只是显示Segmentation Fault,绝对没有更多信息
-
我应该提供什么样的输入?
-
输入阶段还没到!编译后尝试执行它会显示分段错误!
-
@lucifer 这不应该发生。您的算法不正确(如下 gnawux 解释),但程序应该启动并显示程序没有错误。您正在使用哪些编译器/编译器选项?
-
那你为什么让我们看搜索代码?您需要了解如何创建 SSCCE (Short, Self-Contained, Correct Example)。其中一个主要部分是去除多余的东西。 ——现已修复;谢谢!
标签: c linux data-structures segmentation-fault