function - C: Variable is uninitialized for linked list -
i'm relatively new c , creating program involves linked-list. here abbreviated version of code that's giving me trouble.
#include <string.h> #include <stdio.h> #include <stdlib.h> #define strlen 100 struct gene { int num[4]; struct gene *next; }; typedef struct gene item; void build_list(item *current, item *head, file *in); int main() { file *input; file *output; input = fopen("test.data", "r"); output = fopen("test.out", "w+"); item *curr; item *head; head = null; int i; build_list(curr, head, input); curr = head; while(curr) { (i = 0; < 4; ++i) fprintf(output, "%d\n", curr->num[i]); curr = curr->next; } fclose(input); fclose(output); free(curr); } void build_list(item *current, item *head, file *in) { char gene[strlen]; char *tok; char gene_name[strlen]; char *search = ","; int j; while (fgets(gene, sizeof(gene), in)) { current = (item *)malloc(sizeof(item)); tok = strtok(gene, search); strcpy(gene_name, tok); (j = 0; j < 4; ++j) { tok = strtok(null, search); current->num[j] = atoi(tok); } current->next = head; head = current; } }
when try compile this, says variable curr
uninitialized, when initialize malloc
throws segmentation fault, or prints out nothing @ all. why be?
@sourav ghosh have explained wrong code , suggested 1 way solve it. here way.
instead of passing current
, head
variables changed inside function (i.e. pointer-to-pointer), recommend use function return value. in way don't have use pointer-to-pointer.
something like:
item* add_item(item* head) { // place 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)) { // new item head = add_item(head); // fill data new item tok = strtok(gene, search); strcpy(gene_name, tok); (j = 0; j < 4; ++j) { tok = strtok(null, search); head->num[j] = atoi(tok); } } return head; }
and main
call like:
head = null; head = build_list(head, input);
note: readability, skipped check failing malloc
. in real code should check whether malloc
returned null.
Comments
Post a Comment