0

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

1 Answers1

0

You have to pass pointers to values instead of values to fscanf (note the &-signs in &temp->id and &temp->gpa; the char[]-types lname and fname automatically decay to a pointer):

while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, &temp->id, &temp->gpa) != EOF) {
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • Can't believe I missed that. Thank you! I am used to java and keep forgetting the syntax. Will accept answer when it allows me to. – Burton Feng Feb 08 '17 at 21:58
  • To clarify, the name of a char array is roughly equivalent to the variable that holds the first address of the char array; but the name of an integer or float is roughly equivalent to the value of the integer or float. This means you must explicitly indicate the address of the name of the integer or float, while you can use the shorthand name of the array without the "address of" operator. – Edwin Buck Feb 08 '17 at 21:59
  • @EdwinBuck Got it! Keep forgetting to do this, too used to java! – Burton Feng Feb 08 '17 at 22:08