我已经搜索了这个网站以及其他许多人,因为这个看似常见的崩溃让人感觉不到,而且我已经读过这个错误意味着我的代码中的一行正在尝试访问解除分配的内存
我是这种语言的初学者,我正在尝试使用数组来完全理解它们,而我似乎无法弄清楚我的错误是什么。
我会尽量让它变得简单明了:我的程序只是要求:
我的代码如下:
void moyenne()
{
string subjects[0];
double grade[0];
int lim;
cout << "**Program which calculates the average grade of several subjects, each with coefficient 1 **\n";
cout << "How many subjects are you going to enter grades for?\n";
cin >> lim; // User enters the "limit" to which the "for" loop is going to end
cout << "Please enter seperately the subjects of the grades you'd like to enter followed with their respectful grade.\n";
for (int i = 0; i<=lim-1; i++) // "lim-1" because if lim = x, i will go from 0 to x which is x+1 array slots
{
cout << "Enter subject.\n";
cin >> subjects[i];
cout << "Enter grade for " << subjects[i] << ".\n";
cin >> grade[i];
}
for (int j = 0; j<=lim-1; j++)
{
cout << subjects[j] << grade[j];
}
}
该程序系统而精确地在第三次成绩请求时崩溃,无论用户输入lim
只要lim > 2
。错误是:
控制台是:
**Program which calculates the average grade of several subjects, each with coefficient 1 **
How many subjects are you going to enter grades for?
3
Please enter seperately the subjects of the grades you'd like to enter followed with their respectful grade.
Enter subject.
Maths
Enter grade for Maths.
15
Enter subject.
Physics
Enter grade for Physics.
17
Enter subject.
English
(lldb)