gpt4 book ai didi

c++ - 动态分配的结构

转载 作者:行者123 更新时间:2023-11-28 00:27:14 24 4
gpt4 key购买 nike

所以我在这里遇到了麻烦。当我为 numStudents 输入 1 但出现段错误时,该程序工作得很好:11 当我再为 numstudents 输入 1 时。我在动态分配上做错了什么吗?我只是迷路了,已经做了我能想到的一切。

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

最佳答案

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

info->score = new double[numTests];

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

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

但是所有这些都非常容易出错 - 我建议您研究可以为您处理所有这些的结构,例如 std::vector

关于c++ - 动态分配的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24399286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com