Jordan McPeek
Jordan McPeek

Reputation: 9

Dynamically Allocated Structures

So i am having troubles here. The program works perfectly fine when i enter in 1 for numStudents but get a segmentation fault: 11 when i enter anymore that 1 for numstudents. Am i doing something wrong with the dynamic allocation? I am just lost have done everything i can think of.

#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;
}

Upvotes: 0

Views: 78

Answers (1)

Michael Anderson
Michael Anderson

Reputation: 73480

You need to repeat this for each student

info->score = new double[numTests];

So you could move it into the loop:

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

But all this is very error prone - I suggest you look into structures that can handle all this for you like std::vector.

Upvotes: 3

Related Questions