I am trying to implement a graph which will have an integer value as data. Here the problem seems to be that the program is not able to manipulate the ptr pointer in the insertNode funtion and hence it is not excuting the statement ptr->connectsTo=pointer[j];. I am storing the nodes in an array of struct node *pointers. Each node then points to a link list which contains the edges which in turn contain a reference to the node that node is connected to. Its a manipulation of adjacency lists. I have tried a lot. Please help.Also do explain why this behaviour is taking place? This implementation is in relation to 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). Learn how to use the debugger (gdb)