I'm trying to create adjacency list to represent a graph from a list of edges in file "input.txt". I know the basics of how pointers work but I have problem with dynamic struct array which consists of singly linked lists.
#include <stdio.h>
#include <stdlib.h>
struct list {
int vertex;
struct list *next;
};
void create_list(int v, struct list* **array);
int main()
{
int i, v = 5;
struct list *ptr, **array = (struct list **)malloc(sizeof(struct list *) * v);
for (i = 0; i < v; i++)
array[i] = NULL;
array[i] = NULL;
create_list(v, &array);
for(i = 0; i < v; i++) {
ptr = array[i];
printf("%d: ", i);
while(ptr != NULL) {
printf(" ->%d", ptr->vertex);
ptr = ptr->next;
}
printf("\n");
}
return 0;
}
void create_list(int v, struct list* **array)
{
int m, n;
struct list *ptr, *tmp;
FILE *luki;
luki = fopen("input.txt", "r");
while(fscanf(luki, "%d %d\n", &m, &n) == 2) {
tmp = (struct lista*)malloc(sizeof(struct list));
tmp->vertex = n;
tmp->next = NULL;
if (*array[m] == NULL) //Here my program crashes when m changes from 0 to 1
*array[m] = tmp;
else {
ptr = array[m];
while(ptr->next != NULL)
ptr = ptr->next;
ptr->next = tmp;
}
}
fclose(luki);
}
Could you please help me figure out how it should look like?
Also, at first I made the function without using pointer to array:
void create_list(int v, struct list **array)
create_list(v, array);
And it worked really good when debugging and (I'm using CodeBlocks):
0: 4 ->3 ->1
1: 2
2: 3
3:
4:
but while running the program normally I got this:
0:
1:
2:
3:
4:
Why the output while debugging was right if passing array to function create_list was wrong?