-2

When I go to run this within my terminal it will simply tell me it is a segmentation fault. This program reads in a file called DATA. This is a txt file that contains exam scores. The scores go as following (if at all relevant): 10 25 50 50 5 0 0 45 45 15 25 50 2 50 30 40.

    #include <stdio.h>
int main()
{
    FILE *fp = fopen("DATA", "r");   //Opens the file DATA in read mode.
    int possibleScoreCounts[51] = {0};
    int score;
    while(!feof(fp))
    {
       fscanf(fp, "%d", &score);
       possibleScoreCounts[score]++;
    }
    printf("Enter a score to check on the exam: ");
    scanf("%d", &score);
    while(score != -1)
    {
       int count = 0;
       for(int i = 0; i < score; i++)
           count = count + possibleScoreCounts[i];
       printf("%d scored lower than %d\n", count, score);
       printf("Enter a score to check on the exam: ");
        scanf("%d", &score);
    }
}
  • 3
    Don;t use [`!feof(fp)`](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – user2736738 Mar 05 '18 at 18:30
  • 1
    Your entered score is less than `51`? Mention what did you give as input. Check the return value of `fopen`. – user2736738 Mar 05 '18 at 18:32
  • Compile with all warnings and debug info: `gcc -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/). Check against failure of every function, notably `fopen`. Read the documentation of every [IO function](http://en.cppreference.com/w/c/io) that you use. [use the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/). See also [this](https://stackoverflow.com/a/46239896/841108) – Basile Starynkevitch Mar 05 '18 at 18:37
  • 1
    Possible duplicate of [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – JGroven Mar 05 '18 at 18:39
  • 1
    @JGroven Well, if we would mark every segfault as dupe of this one... we could close SO (well, the C part of it at least) – Eugene Sh. Mar 05 '18 at 18:41
  • @EugeneSh. If everyone would read that post, perhaps we wouldn't see the question "Why am I getting a segfault?" ever again, and maybe as a result we'd see some C questions that have positive scores again. – JGroven Mar 05 '18 at 18:43
  • You don't check `fopen`, `fscanf`, or `scanf` for errors. Add that immediately so you aren't missing obvious problems. – David Schwartz Mar 05 '18 at 19:35

1 Answers1

0

your code compiles under c99 to compile it with out move i declatration outside the for

I tested this on my system and it works (as far as logic goes)

This means that one of the specific functions fopen, fscanf, or scanf failes - you must check error values

Omer Dagan
  • 662
  • 5
  • 14