![](/img/trans.png)
[英]Why am I getting the Segmentation fault (core dumped) error in my program when using 2d arrays?
[英]Why am I getting segmentation fault (core dumped) error in my code?
此代码用于使用邻接表创建图形。
node
是垂直链表每个元素的水平链表结构,
而graphnode
是垂直链表的结构。
代码编译正确,但是当给出第一个输入时,它在它之后显示分段错误。
#include<iostream>
using namespace std;
struct node //struct
{
struct node *next;
char value;
};
struct graphnode
{
struct node *start;
struct graphnode *down;
char value;
int count;
};
graphnode * creategraphnode(char val)
{
struct graphnode *newnode=new graphnode;
newnode->start=NULL;
newnode->down=NULL;
newnode->value=val;
newnode->count=0;
return newnode;
}
node *createnode(char val)
{
struct node *newnode=new node;
newnode->next=NULL;
newnode->value=val;
}
void insertgraphnode(char value,graphnode *graph)
{
struct graphnode *newnode=creategraphnode(value);
if(graph==NULL)
{
graph=newnode;
}
else
{
graphnode *temp=graph;
while(temp->down)
temp=temp->down;
temp->down=newnode;
}
}
void insertnode(graphnode *graph)
{
char val;
struct node *temp=graph->start;
cout<<"What is the outdegree of "<<graph->value;
cin>>graph->count;
cout<<"\nEnter"<<graph->count<<" nodes separated by space:";
for(int i=1;i<=graph->count;i++)
{
cin>>val;
node* newnode=createnode(val);
temp=newnode;
temp=temp->next;
}
}
void display(struct graphnode *graph)
{
if(graph==NULL)
{
cout<<"\nNo data to display";
return;
}
struct graphnode *temp=graph;
while(temp)
{
struct node *temp1=temp->start;
cout<<temp->value<<"=>> ";
if(temp1==NULL)
{
continue;
}
else
{
while(temp1)
{
cout<<temp1->value<<"-> ";
temp1=temp1->next;
}
}
cout<<"/\n";
}
}
int main()
{
struct graphnode *graph=NULL;
int totalnodes;
char val;
cout<<"\nHow many nodes does the graph contain? : ";
cin>>totalnodes;
cout<<"\nEnter "<<totalnodes<<" space separated nodes : ";
for(int i=1;i<=totalnodes;i++)
{
cin>>val;
insertgraphnode(val,graph);
}
struct graphnode *temp=graph;
while(temp->down)
{
insertnode(temp);
temp=temp->down;
}
display(graph);
return 0;
}
如果我没记错的话,你的代码至少有三个问题。
1)您的createnode()
不返回创建的节点; 添加return newnode;
2)您的insertgraphnode()
不更改调用函数中的第二个参数; 所以,当你在main()
调用它时
insertgraphnode(val,graph);
graph
NULL
; 在insertgraphnode()
内更改值但在函数graph
保持NULL
; 曾经。 这会导致分段错误。
您可以解决这个不断变化的insertgraphnode()
因此第二个参数是一个指向指针的指针并传递&graph
。
另一种解决方案是修改insertgraphnode()
以返回graph
值
graphnode * insertgraphnode(char value,graphnode *graph)
{
struct graphnode *newnode=creategraphnode(value);
if(graph==NULL)
{
graph=newnode;
}
else
{
graphnode *temp=graph;
while(temp->down)
temp=temp->down;
temp->down=newnode;
}
return graph;
}
并以这种方式调用它
graph = insertgraphnode(val,graph);
3) while
在display()
去中环,因为你不改变的值temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.