@Sourav Ghosh have already explained what was wrong with your code and also suggested one way to solve it. Here is another way.
Instead of passing current
and head
as variables to be changed inside the function (i.e. as pointer-to-pointer), I would recommend that you use the function return value. In that way you don’t have to use pointer-to-pointer.
Something like:
item* add_item(item* head)
{
// Place a new item in front
item* current = malloc(sizeof(item));
current->next = head;
return current;
}
item* build_list(item* head, FILE *in) {
char gene[STRLEN];
char *tok;
char gene_name[STRLEN];
char *search = ",";
int j;
while (fgets(gene, sizeof(gene), in))
{
// Get a new item
head = add_item(head);
// Fill data into the new item
tok = strtok(gene, search);
strcpy(gene_name, tok);
for (j = 0; j < 4; ++j)
{
tok = strtok(NULL, search);
head->num[j] = atoi(tok);
}
}
return head;
}
and from main
call it like:
head = NULL;
head = build_list(head, input);
Note: For readability, I skipped all check for failing malloc
. In real code you should always check whether malloc
returned NULL.
solved C: Variable is uninitialized for linked list