在洛谷刷题遇到如下问题:
在下列代码中,当定义类数组为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;
}
}