Why am I getting a Segmentation fault?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • carlymb
    New Member
    • Mar 2011
    • 2

    Why am I getting a Segmentation fault?

    I Have written this code for a programming assignment in a C/C++ class and I can not find were it is having problems
    *************** ***
    Code:
    struct student
    {
    char last_name[20];
    char frist_name[20];
    float points;
    char grade;
    };
    ...
    void sort(struct student list[], int n)
    ...
    fp1=fopen(argv[1], "r");
    ...
    while(check!=EOF)
    {
    n++;
    check=fscanf(fp1, "%s %s %d",list[n].last_name,
    list[n].frist_name, list[n].points);
    }
    compute_grade(list,n);
    sort(list, n);
    ...
    }
    *************** *******
    complete code attached.
    I think the problems with how I pass the list but I am not sure the error when I put the the FILE with the following data
    Smith John 90.00
    Willis Josh 60.50
    Apple Kate 75.33
    Ford Mary 85.45

    is a Segmentation fault
    not very much help I know
    any step in the right direction will be a great help.
    Attached Files
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    you need to pass addresses to fscanf using the & address of operator
    Code:
    check=fscanf(fp1, "%s %s %d",&list[n].last_name,
        &list[n].frist_name, &list[n].points);

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      No you need to pass the address of variables with types like int and float. Since a string is an array the array name already decays to a pointer. Also you use %d which indicates an integer but .points is a float.

      Try

      Code:
      check=fscanf(fp1, "%s %s %f",list[n].last_name,
          list[n].frist_name, &list[n].points);

      Comment

      • carlymb
        New Member
        • Mar 2011
        • 2

        #4
        how would I need to pass the array though to compute grade to actually make the change?

        Comment

        Working...