I am trying to do an exercise on C. There are two arrays, count and list. count is an array of ints initially filled with 0, while list is an array of queues. My code is supposed to take pairs of numbers separated by a space eg. "1 2". For every pair of numbers, I must add 1 to the 2nd number-1 position in the count array, and then put a node containing the 2nd number in the head of the queue in the 1st number-1 position of the list array. My code is down below, and it results to a segmentation error after receiving the first pair of numbers. Removing lines 24-30 removes the error, but I don't understand what causes this error. Can anyone point out why it's doing a segmentation error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node Node;
struct node {
int succ;
Node *next;
};
void set_initial_array(int count[], int n, Node *list[]);
void handle_input(char string[], int count[], Node *list[]);
void set_initial_array(int count[], int n, Node *list[]) {
for (int i = 0; i < n; i++) {
count[i] = 0;
list[i] = NULL;
}
}
void handle_input(char string[], int count[], Node *list[]) {
int j = atoi(&string[0]), k = atoi(&string[2]);
count[k - 1]++;
if (list[j - 1] != NULL) { // Removing line 24-30 removes error
Node head = {k, list[j - 1]};
list[j - 1] = &head;
} else {
Node head = {k, NULL};
list[j - 1] = &head;
}
}
int main() {
char string[4];
int count[15];
Node *list[15];
set_initial_array(count, n, list); //fill count with 0 and list with NULL
while (fgets(string, 4, stdin) != NULL && strcmp(string, "0 0") != 0) {
handle_input(string, count, list);
}
}
ninmain?