【发布时间】:2014-12-02 15:39:21
【问题描述】:
我正在尝试实现一个将整数值作为数据的图形。这里的问题似乎是程序无法在 insertNode 函数中操作 ptr 指针,因此它没有执行语句 ptr->connectsTo=pointer[j];。我将节点存储在 struct node *pointers 数组中。然后每个节点指向一个链接列表,该链接列表包含边,边又包含对该节点所连接的节点的引用。它是对邻接列表的操作。我已经尝试了很多。请帮助。还要解释为什么会发生这种行为?此实现与http://www.spoj.com/problems/BUGLIFE/ 相关。
#include<stdio.h>
#include<malloc.h>
#include<ctype.h>
#include<stdlib.h>
struct node
{
int data;
int visited;
struct link_edges *edges;
};
struct link_edges
{
struct node *connectsTo;
struct link_edges *next;
};
struct node *head = NULL;
struct node *pointer[2002];
void insertNode(int i,int j)
{
struct node *temp=NULL;
temp = (struct node *)malloc(sizeof(struct node));
struct link_edges *ptr;
ptr = (struct link_edges *)malloc(sizeof(struct link_edges));
struct node *tempo;
tempo = (struct node *)malloc(sizeof(struct node));
//struct link_edges *temporary;
//temp = (struct link_edges *)malloc(sizeof(struct link_edges));
if(pointer[i]==NULL)
{
temp->data=i;
temp->visited=-1;
temp->edges=NULL;
ptr=temp->edges;
pointer[i]=temp;
}
else
{
ptr = pointer[i]->edges;
}
while(ptr!=NULL)
{
ptr=ptr->next;
}
tempo->data=j;
tempo->edges=NULL;
tempo->visited=-1;
pointer[j]=tempo;//from this line onwards runtime error is originating. I am unable to print values beyond this line thats how i know the runtime error.
ptr->connectsTo=pointer[j];
ptr->next=NULL;
}
int main()
{
int t,n,m,bugs[2002],a,b,flag,i;
int count;
scanf("%d",&t);
count = 0;
while(t--)
{
for(i=1;i<=2000;i++)
{
bugs[i] = 0;
pointer[i]=NULL;
}
flag=1;
scanf("%d %d", &n, &m);
while(m--)
{
scanf("%d %d", &a, &b);
if(bugs[a]==0&&bugs[b]==0)
{
insertNode(a,b);
bugs[a]=1;
bugs[b]=1;
}
else if(bugs[a])
{
}
else if(bugs[b]==0)
{
}
else
{
}
}
if(flag==0){
printf("Scenario %d:\n",++count);
printf("Suspicious bugs found!\n");
}
else{
printf("Scenario %d:\n",++count);
printf("No suspicious bugs found!\n");
}
}
}
【问题讨论】:
-
编译时包含所有警告和调试信息 (
gcc -Wall -Wextra -g)。了解如何使用调试器 (gdb)
标签: c graph segmentation-fault runtime-error adjacency-list