0

This simple program to read the grade of students. I want to take how many students the user want to enter, but when I'm writing int g[size];it will be compilation error! I wonder how can I write it correct?

#include <iostream> 
using namespace std;

    int main()
    {
        int x;
        cout << "Enter how many student ..?  ";
        cin >> x;
         const int size = x;
        int g[size];
        cout << "enter " << size << "your ";
        for (int i = 0; i < size; i++){
            cin >> g[i];
        }
        for (int i = 0; i < size; i++){
            cout << "student" << i + 1 << "grade is : " << g[i] << endl;
        }

   system("pause");
    return 0 ;
}
Khan
  • 53
  • 1
  • 7

1 Answers1

1

The line int g[size]; causes a compile error because size is not known at compile time (but obviously at runtime). So you need to allocate memory for the array at runtime.

int *g = new int[size]; // instead of int g[size];

This stores a pointer to the first element of the array in g. Now the compiler can no longer track the lifetime of the array and delete it for you when it isn't needed anymore so you need to do this yourself as well.

delete[] g; // this frees the memory again
system("pause");

As a side note: Your program is valid C++14 which is not yet (fully) supported by Microsoft's Visual C++ compiler but other compilers like clang and g++ already support it.

Salfurium
  • 41
  • 3