gpt4 book ai didi

c++ - gcc 中的指针导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:39:17 27 4
gpt4 key购买 nike

我正在尝试使用以下代码实现一个链表,我遇到了段错误错误,请告诉我问题出在哪里。

我正在使用 ubuntu gcc 编译器,请给我一些建议

#include<iostream>

using std::cout;
using std::cin;


class ll
{
struct node
{
int info;
node *nextnode ;
}*n;



public:
ll()
{
n=NULL;
}

void getinfo()
{
node *temp,*r;


if( n==NULL )
{
temp=new node;
cout<<" \n enter the first elements of linklist \n";
int z;
cin>>z;
//i guess problem starts here
temp->info=z;
cout<<"the value of info is";
temp->nextnode = NULL;
n=temp;
}
else{
temp=n;
cout<<"heheh balls";
while(temp->nextnode==NULL)
{
temp=temp->nextnode;
}
r=new node;
cout<<"enter the element \t";
int y;
cin>>y;
r->info=y;
r->nextnode=NULL;
temp=r;
}
}

void display()
{
node *temp=n;
while(temp->nextnode==NULL)
{
cout<<temp->info;

}
}

};

int main()
{
ll p;
int v;
cout<<"enter the number of elements to be added to linklist \t";
cin>>v;
//tryn to input linklist from terminal
for(int i=0;i<v;i++)
{
p.getinfo();
}
p.display();

return 0;
}

最佳答案

while(temp->nextnode==NULL)
{
temp=temp->nextnode;
}
....
temp=r;

应该是

while(temp->nextnode!=NULL)
{
temp=temp->nextnode;
}
....
temp->nextnode=r;

同样适用:

void display()
{
node *temp=n;
while(temp->nextnode==NULL)
{
cout<<temp->info;

}
}

应该是:

void display()
{
node *temp=n;
while(temp!=NULL)
{
cout<<temp->info;
temp = temp->nextnode;
}
}

关于c++ - gcc 中的指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100228/

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