Using cin to define the size of an array.

Hello again, This following question is merely for my own gratification.
I understand that the following code is illegal on many compilers and I was told so many times by my instructors, but what I don't really understand is why.
Is it because of security risk? Is it inefficient? I won't ever try to use this notation, but I am curious as to what disallows it.

1
2
3
        cout << "Enter number of students: \n";
        cin >> number;
        int score[number];
Because automatic variables must have their size known at compile time. You can allocate an array dynamically but you'll have to delete it as well:
1
2
3
4
5
cout << "Enter number of students: \n";
cin >> number;
int *score = new int[number]; // allocate memory
// use it ...
delete[] score; // free memory 
A better alternative is std::vector:
1
2
3
4
5
6
#include <vector>
//...
cout << "Enter number of students: \n";
cin >> number;
std::vector<int> score ( number );
// use it ... 
http://www.cplusplus.com/reference/stl/vector/
Topic archived. No new replies allowed.