gpt4 book ai didi

C++ 链表核心转储错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:21 25 4
gpt4 key购买 nike

尝试做一个简单的链表程序,得到段错误(核心转储)错误,任何人都可以帮助解决这个问题。无法理解指针到底在哪里搞砸了。

你能建议任何其他有效的方法来写这个吗

#include<iostream>
using namespace std;

struct node{
int x;
node *next;
}*head=NULL,*temp=head;


class list{
public:
list(){
temp=head;
}
//is something happening here causing core dump?
void addnode(int value){
if (head==NULL)
{
head->x=value;
head->next=NULL;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
temp->next=new node;
temp=temp->next;
temp->x=value;
temp->next=NULL;
}
}

void print(){
while (temp->next!=NULL)
{
cout<<temp->x<<" ";
temp=temp->next;
}
}
};

int main()
{
list l=list();
l.addnode(12);
l.addnode(23);
l.print();
return 0;
}

最佳答案

你忘了分配对象

void addnode(int value){
if (head==NULL)
{
head = new node; //here was a mistake
head->x=value;
head->next=NULL;

同时删除全局临时变量并使用本地

else
{
node *temp = head;
while(temp->next!=NULL)
temp=temp->next;

}

void print(){
node *temp = head;
while (temp!=NULL) // here mistake too
{
cout<<temp->x<<" ";
temp=temp->next;
}
}

关于C++ 链表核心转储错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com