Read data from a file into an array – C++

The issue is that you’re declaring a local grades array with a size of 1, hiding the global grades array. Not only that, you are now accessing the array beyond the bounds, since the local grades array can only hold 1 item.

So get rid of the line:

int grades[i];

However, it needs to be mentioned that this:

int i = 0;
int grades[i];

is not valid C++ syntax. You just stumbled into this by mistake, but that code would not compile if compiled using a strict ANSI C++ compiler.

An array in C++ must be declared using a constant expression to denote the number of entries in the array, not a variable. You, by accident, are using a non-standard compiler extension called Variable Length Arrays or VLA’s for short.

If this is for a school assignment, do not declare arrays this way (even if you meant to do it), as it is not officially C++. If you want to declare a dynamic array, that is what std::vector is for.

Leave a Comment