图实现中的C运行时错误

时间:2014-12-02 15:39:22

标签: c graph segmentation-fault runtime-error adjacency-list

我正在尝试实现一个具有整数值作为数据的图形。这里的问题似乎是程序无法操作insertNode函数中的ptr指针,因此它没有激发语句ptr-> connectionsTo = pointer [j] ;.我将节点存储在struct node *指针的数组中。然后,每个节点指向一个包含边的链接列表,这些边又包含对节点所连接节点的引用。它是对邻接列表的操纵。我已经尝试了很多。请帮忙。还要解释为什么会发生这种行为?此实现与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");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为使用ptr变量存在问题。

在您调用它的位置的insertNode()中

ptr->connectsTo=pointer[j];

ptr将始终为NULL,因为之前的循环在ptr为NULL之前不会退出:

    while(ptr!=NULL)
    {
        ptr=ptr->next;
    }

因此,您将获得运行时空指针错误。不确定你在尝试使用该循环,但需要重新考虑它。也许你打算用?

while(ptr->next !=NULL)