简体   繁体   中英

Fscanf giving a segmentation fault

I have spent a couple hours trying to figure out what was wrong with this code. I've tried using putting the code in a feof while loop, as well as taking the fscanf out of the loop so that it only runs once. These changes still provoke the segmentation fault, even though the data in the files are valid.

struct student *temp = (ident*) malloc (sizeof(ident));
while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, temp->id, temp->gpa) != EOF) {
    if(head == NULL)
        head = temp;
    else {
        struct student *traverse = head;
        while(traverse->next != NULL)
            traverse = traverse->next;
        traverse->next = temp;
        printf("added");
    }
}

The following is the struct:

struct student{
char fname[256];
char lname[256];
unsigned int id;
float gpa;
struct student *next;
};

An example of a line on the text file:

john doe 1 3.6

john smith 3 2.4

您必须传递指向值的指针,而不是传递给fscanf的值(请注意, & temp- &temp->id&temp->gpa中的&temp->id &符号; char[] -types lnamefname自动衰减为指针):

while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, &temp->id, &temp->gpa) != EOF) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM