質問

The program should generate a graph and store its neighbours in an adjacency list. I get a SEGFAULT while parsing the list. It's so strange because when I try to access the list one by one, it works alright.

My code:

int main(void) 
{   

    typedef struct linkedList{
        int vertice;
        struct linkedList *next;
    }LL;

    typedef struct vertex{
        int color;
        int noOfNeighbours;
        LL *adj;
    }vertex;

    int E, V;

    scanf ("%d %d", &V, &E);
    //printf ("%d %d", E, V);

    int i, j; //loop variables

    vertex arrOfVertices [V];

    for (i=0; i<V; i++)
    {
        arrOfVertices[i].color=-1; 
        arrOfVertices[i].noOfNeighbours=-1;
        arrOfVertices[V].adj = NULL;
    }
    printf ("Output is : \n");
    int firstV, secondV;
    for (i=0; i<E;i++)
    {
        scanf ("%d %d", &firstV, &secondV);
        LL* temp = malloc (sizeof(LL));
        temp -> vertice = secondV-1;
        if (arrOfVertices[firstV-1].adj == NULL)
        {
            arrOfVertices[firstV-1].adj=temp;
            arrOfVertices[firstV-1].adj->next=NULL;
        }
        else
        {
            temp->next=arrOfVertices[firstV-1].adj;
            arrOfVertices[firstV-1].adj=temp;
        }
    }

    //Printing the list function. This part strangely segfaults and I don't know why
    for (j=0; j<V;j++)
    {
        LL* parser = arrOfVertices[j].adj;
     // printf ("%d : Color: %d\n", i+1, arrOfVertices[i].color);

        while (parser!=NULL)
        {
            printf ("%d\n", parser->vertice);
            parser = parser->next;
        }
    }

    return 0;
}
役に立ちましたか?

解決 2

The error was at arrOfVertices[V].adj = NULL;, it worked when changed to arrOfVertices[i].adj = NULL;. Typo Error. Phew! Thanks, @Whoami and @WhozCraig for pointing it out. :)

他のヒント

In your code, it seems you are wanting to define an array of size V, where the actual value of V is entered by the user. However, in C, the compiler needs to know the size of arrays in advance. C might let you place a type and variable declaration in any order, but that does not mean that this will be the order of execution.

If you must use an array, you need to set up a size of the array in advance, and check that it is large enough for the values entered. Or, you need to create a pointer to an Array of vertex. Then, after the user has entered V, you need to build as many structures as asked for by the user by using malloc and sizeof(vertex) as you(?) did in the later portion of the program.

p.s. As whoamI mentioned, you are also going to incur an out of bounds reference in line arrOfVertices[V].adj = NULL; Arrays in C are 0-based, so if V is 5, and you (by the methods above) generated 5 vertices, you must refer to the last vertex, as arrOfVertices[4].

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top