Variable changes midway through loop and I can't figure out what's the problem

Viewed 45

I'm writing some code to calculate GPA and when I start a loop, one of my variables "numClasses" changes value to a huge number midway through the loop and I can't figure out what's going on.

#include <stdio.h>

int main()
{
  float crdtHrs[] = {}; //Credit hours for this term
  float numClasses; //Amount of classes taken this term
  float qltyPoints[] = {}; //Quality points for term
  float classes[] = {}; //Array for class grades

  printf("Please enter total number of classes -> ");
  scanf("%f", &numClasses);

  float a = numClasses; //using new variable because this way the loop works

  for(int i = 1; i <= a; i++)
  {
    printf("\nGPA class #%d -> ", i);
    scanf("%f", &classes[i - 1]);
    printf("Credit hours for course -> ");
    scanf("%f", &crdtHrs[i - 1]);
    printf("%f", numClasses); //at some point of my loop numClasses changes value
  }

  return(0);
}
1 Answers

Nice zero length array buffer overrun. Boom. Let's arrange so the arrays are declared a little later so we can give them sizes.

  printf("Please enter total number of classes -> ");
  scanf("%f", &numClasses);
  int a = (int)numClasses;

  float crdtHrs[a]; //Credit hours for this term
  float qltyPoints[a]; //Quality points for term
  float classes[a]; //Array for class grades

Now we allocate the arrays on the stack at the right size.

Related