-1

I would like to know why the loop below just execute one time? Here is my code.

for(i=0;i<MAX;i++)
{
    printf("name:");
    gets(student[i].name);
    printf("math score:");
    scanf(" %d",student[i].math);
    fflush(stdin);        
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Kevin Chen
  • 19
  • 2
  • Does your program terminate normally, or with an error? – Codo Jun 27 '22 at 10:38
  • Please provide a complete, reproducible example. – Codo Jun 27 '22 at 10:38
  • 1
    Well, with the [gets](https://stackoverflow.com/q/1694036/10871073) call and [fflush(stdin)](https://stackoverflow.com/q/2979209/10871073), even running the loop once is most likely once too often. ;( – Adrian Mole Jun 27 '22 at 10:38
  • Probably `gets(student[i].name);` writes out of bounds and so overwrites `i`. – mch Jun 27 '22 at 10:39

1 Answers1

1

At least the code contains a typo. You have to write

scanf(" %d", &student[i].math);
            ^^^

Also this call

fflush(stdin);        

has undefined behavior.

And the function gets is unsafe and is not supported by the C Standard. Instead use function fgets or scanf.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335