I'm relatively new to C and I was creating a program that involves a linked-list. Here is a very abbreviated version of the 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) {
for (i = 0; i < 4; ++i)
fprintf(output, "%d
", 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);
for (j = 0; j < 4; ++j) {
tok = strtok(NULL, search);
current->num[j] = atoi(tok);
}
current->next = head;
head = current;
}
}
When I try to compile this, it says variable curr
is uninitialized, but even when I initialize it with malloc
it throws a segmentation fault, or it prints out nothing at all. Why could this be?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…