动态分配的结构

时间:2014-06-25 02:31:18

标签: c++ structure dynamic-allocation

所以我在这里遇到了麻烦。当我为numStudents输入1但是得到分段错误时,该程序工作得很好:11当我再输入1为numstudents时。我是否在动态分配方面做错了什么?我只是失去了我能想到的一切。

#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>

using namespace std;

//Structure Declaration
struct Student
{
    string name;
    long long ID;
    double *score;
};

//Function prototypes
void calcAvg (int loc, Student test[], double average[], int tests);

int main()
{
    int numStudents, numTests;  //Get from user
    double  *averages;  //For Dynamic allocation of averages
    Student *info;  //For Dynamic Allocation

    cout << "Enter the number of students you will enter ";
    cin >> numStudents;

    info = new Student[numStudents];
    averages = new double[numStudents];

    cout << "\nEnter the number of tests that were taken by the students ";
    cin >> numTests;

    info->score = new double[numTests];

    for(int s = 0; s < numStudents; s++)
    {
        cout << "Enter student #" << (s+1) << "'s name ";
        cin.ignore();
        getline(cin, info[s].name);
        cout << "Enter " << info[s].name << "'s ID number ";
        cin >> info[s].ID;
        cout << endl;

        for(int t = 0; t < numTests; t++)
        {
            cout << "\nEnter " << info[s].name << "'s score for test #" <<(t+1) << " ";
            cin >> info[s].score[t];

            while(info[s].score[t] > 100 || info[s].score[t] < 0)
            {
                cout << "The score you entered is invalid, try again. ";
                cin >> info[s].score[t];
            }
        }

    calcAvg(s, info, averages, numTests);
    }

    return 0;
}


void calcAvg (int loc, Student test[], double average[], int tests)
{
    double total = 0;

    for(int i = 0; i < tests; i++)
    {
        total += test[loc].score[i];
    }
    average[loc] = total/tests;

    cout << average[loc] << endl;
}

1 个答案:

答案 0 :(得分:3)

你需要为每个学生重复这个

info->score = new double[numTests];

所以你可以把它移到循环中:

for(int s = 0; s < numStudents; s++)
{
   info[s].score = new double[numTests];
   ...
}

但这一切都非常容易出错 - 我建议你研究一下可以为你处理所有这些问题的结构std::vector