c++数组段错误产生的原因?

在洛谷刷题遇到如下问题:
在下列代码中,当定义类数组为stu[n+5]时,得到16分,提示段错误,错误提示信息如下:

Runtime Error. Received signal 11: Segmentation fault with invalid memory reference.

当stu[n+10]时,得到32分,同样提示段错误;
增加到stu[n+100]时才顺利通过了,这是为什么呢?
源码如下:

#include <iostream>
using namespace std;
class Student{
    public:
        string name;
        int year;
        int month;
        int day;
        int statis;
};
int main(){
    int n;
    Student stu[n+100];
    cin >> n;
    for(int i = 0; i < n; i ++){
        cin >> stu[i].name >> stu[i].year >> stu[i].month >> stu[i].day;
        stu[i].statis = stu[i].year*10000 + stu[i].month*100 + stu[i].day;
    }
    for(int i = 0; i < n-1; i ++){
        for(int j = n-1; j > i; j --){
            if(stu[j-1].statis >= stu[j].statis){
                swap(stu[j], stu[j-1]);
            }
        }
    }
    for(int i = 0; i < n; i ++){
        cout << stu[i].name << endl;
    }
}

原第14行放到第13行之前。使用n的值定义结构数组,需要在获取n的值之后。

如果是放在获取n的值之前,n的值是内存位置的随机值,可能是0,也可能是别的值,然后定义的数组大小可能小于需要测试的大小,就会报错了。

Student stu[n+100];
这样是错误的。应该定义为Student stu[100]。当你不确定多大时,把100改为更大的数字就行了

数组越界的问题,看到已解决就不赘述了
加油~~