我正在编写一个程序,使用一组结构来存储一定数量的学生的名字,身份证号码和一系列考试成绩。需要动态分配结构数组和测试分数成员数组。我已经深入到允许用户输入每个学生的考试成绩的功能,但是我在最后一个函数(getScores函数)中遇到了cin问题。使用Linux时我遇到了分段错误,因此我假设它与动态分配的测试数组有关,该数组是结构的一部分,我无法看到它。我想知道如何调试它并解释为什么实际发生这种情况所以我将来可以避免它。
//Preprocessor Directives
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Structure declaration
struct Students
{
string name; //Student name
int idNum; //Student ID number
double *tests; //Pointer to an array of test scores
};
//Function prototypes
Students *getStudents(int &);
double *getTests(int &);
void getInfo(string &, int &, int);
void getScores(double &, string, int);
//Main program section
int main ()
{
int numStudents = 0;
int numTests = 0;
Students *studentFiles = NULL;
//Call the getStudents function
studentFiles = getStudents(numStudents);
//Call the getTests function
studentFiles->tests = getTests(numTests);
for(int i = 0; i < numStudents; i++)
{
//Call the getInfo function
getInfo(studentFiles[i].name, studentFiles[i].idNum, i+1);
}
for(int i = 0; i < numStudents; i++)
{
for(int j = 0; j < numTests; j++)
{
getScores(studentFiles[i].tests[j], studentFiles[i].name, j);
}
}
delete [] studentFiles;
delete [] studentFiels->tests;
return 0;
}
Students *getStudents(int &numStudents)
{
Students *studentFiles = NULL;
//Prompt the user for the number of students
cout<<"Enter the number of students: ";
cin>>numStudents;
//Dynamically allocate an array of structs, one for each student
studentFiles = new Students[numStudents];
return studentFiles;
}
double *getTests(int &numTests)
{
double *tests = NULL;
//Prompt the user for the number of tests
cout<<"Enter the number of tests: ";
cin>>numTests;
cin.ignore();
//Dynamicall allocate an array of integers, one for each test
tests = new double[numTests];
return tests;
}
void getInfo(string &name, int &idNum, int index)
{
//Prompt for each student's name and id number
cout<<"Enter the name of student #"<<index<<": ";
getline(cin, name);
cout<<"Enter the id number of student #"<<index<<": ";
cin>>idNum;
cin.ignore();
}
void getScores(double &test, string name, int numTest)
{
cout<<name<<endl;
cout<<numTest<<endl;
//Prompt for each test score for each student
cout<<"Enter "<<name<<"'s score for test #"<<numTest+1<<": ";
cin>>test;
}
答案 0 :(得分:3)
一个错误是您访问已删除对象studentFiles
的成员。反转线来修复:
delete [] studentFiles->tests;
delete [] studentFiles;
理想情况下,使用std::vector<>
而不是手动分配和释放内存。
另请注意,代码仅初始化数组第一个成员的Student::tests
,其余Student
个对象的此成员未初始化。表达式studentFiles[i].tests[j]
的结果未定义,很可能导致崩溃。
您需要初始化每个Student::tests
的{{1}}成员。完成后,请取消分配Student
中的Student::tests
。