[英]C runtime error in graph implementation
我正在嘗試實現一個將整數值作為數據的圖。 這里的問題似乎是該程序無法在insertNode函數中操作ptr指針,因此無法執行ptr-> connectsTo = pointer [j];語句。 我將節點存儲在結構節點*指針數組中。 然后,每個節點都指向一個鏈接列表,該列表包含邊緣,這些邊緣又包含對該節點連接到的節點的引用。 它是鄰接表的一種操作。 我已經嘗試了很多。 請幫忙。還要說明為什么會發生這種現象嗎? 此實現與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");
}
}
}
我認為ptr變量的使用存在問題。
在insertNode()中,您將其稱為:
ptr->connectsTo=pointer[j];
由於循環之前ptr始終為NULL,直到ptr為NULL才退出:
while(ptr!=NULL)
{
ptr=ptr->next;
}
因此,您將收到運行時空指針錯誤。 不確定要使用該循環做什么,但需要重新考慮。 也許您打算使用?
while(ptr->next !=NULL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.