崩溃错误EXC_bad_access code = 1 address = 0x0

时间:2017-03-14 03:35:05

标签: c++ for-loop crash

我已经搜索了这个网站以及其他许多人,因为这个看似常见的崩溃让人感觉不到,而且我已经读过这个错误意味着我的代码中的一行正在尝试访问解除分配的内存

我是这种语言的初学者,我正在尝试使用数组来完全理解它们,而我似乎无法弄清楚我的错误是什么。

我会尽量让它变得简单明了:我的程序只是要求:

  1. 用户将要输入多少科目和后续成绩
  2. 主题的名称,后跟用户之前输入的数字的等级(因此,如果用户在第一个问题上输入 3 ,该计划将要求 3 输入主题和年级的时间)
  3. 我的代码如下:

    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。错误是:Error screenshot

    控制台是:

    **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)

0 个答案:

没有答案