【发布时间】:2019-01-22 03:20:59
【问题描述】:
# include <iostream>
using namespace std;
struct node{
int data;
node *l,*r,*p;
};
int main(){
int i,n;
cout<<"Enter the number of nodes\n";
cin>>n;
i=1;
while(i<=n){
y=root;
x = (node *)malloc(sizeof(node));
cin>>x->data;
while(y!=NULL){
if(x->data < y->data){
parent = y;
y = y->l;
}
else{
parent = y;
y = y->r;
}
}
if(root==NULL){
root=x;
}
else if(parent->data < x->data){
parent->r = x;
x->p = parent;
}
else{
parent->l = x;
x->p = parent;
}
i++;
}
return 0;
}
它在 iMac 上使用 g++ 命令通过命令窗口给出分段错误,但在其他 IDE(在线和离线 IDE)上工作正常,我什至在我的恶魔个人电脑上尝试了代码,他有 DEV c++ 和它工作正常,我还尝试了在线 IDE(网站:-codechef 等,工作正常)。enter image description here
【问题讨论】:
-
您展示的代码甚至不应该构建,更不用说崩溃了。请read about how to ask good questions 和this question checklist。然后学习如何创建Minimal, Complete, and Verifiable Example 和how to debug your programs。
-
请考虑正确缩进您的代码,使其可读。
-
不要在 C++ 中使用
malloc。 -
root 未声明,即使已声明(如下面答案的注释),它也未初始化,因此您的代码有时会崩溃。
-
请edit你的问题告诉我们你做了什么样的调试。我希望您已经在 Valgrind 或类似的检查器中运行了您的minimal reproducible example,并使用诸如 GDB 之类的调试器进行了调查。确保您也启用了全套编译器警告。这些工具告诉了你什么,它们缺少什么信息?并阅读 Eric Lippert 的 How to debug small programs。
标签: c++ command g++ binary-search-tree