【发布时间】:2019-02-04 14:41:32
【问题描述】:
我正在尝试编写一个简单的程序来将整数值存储在 3 节点链表中,但在我插入第一个值后它显示“分段错误(核心转储)”。
我对 c++ 比较陌生,所以我真的不知道我做错了什么。我已经尝试在 Internet 上搜索解决方案,但我似乎找不到任何解决方案。
#include<iostream>
using namespace std;
struct node{
int num;
node *next;
};
node *head=NULL;
node *tail=NULL;
void create(int num){
node *temp=new node;
temp->num=num;
temp->next=NULL;
if(head=NULL){
head=temp;
tail=temp;
temp=NULL;
}
else{
tail->next=temp;
tail=temp;
}
}
void display(node *current ){
while(current!=NULL){
cout<<current->num<<endl;
current=current->next;
}
}
int main(){
int num;
for(int i=0;i<3;i++){
cout<<"Enter a number:";
cin>>num;
}
display(head);
return 0;
}
感谢任何帮助和/或提示 :)
编辑:好的,所以我看到我错过了 int he if 子句 head 应该是 head==NULL,但现在它最后没有显示链表:(
【问题讨论】:
-
head=NULL应该是head == NULL -
准确来说
if(head=NULL){应该是if (head == NULL) {,node *head=NULL;是可以的。如果您在布局代码时使用几个空格更容易看到这种错误? -
仅供参考,从 c++11 开始,您应该使用
nullptr而不是NULL,并且从 c++11 开始,您不应再使用new或delete,而是使用智能指针用于创建对象和处理对象的所有权。 -
调试器。使用调试器。调试器将允许您单步执行代码,观察变量中的值。通常,使用调试器比正确发布到 StackOverflow 并等待有人为您检查或调试程序要快得多。
标签: c++ linked-list coredump