【发布时间】:2016-01-30 00:54:44
【问题描述】:
我正在使用包含三个字段的 Student 结构。然后我在 main 中声明一个指向 Student 结构的指针。然后我将该指针传递给一个函数。该函数计算文件中有多少行,然后动态分配学生数组,使其与文件中的行数大小相同,然后将数据读入数组。我坚持动态分配 Student 数组,因为函数参数涉及指向结构的指针。
因为函数参数是一个指向结构体的指针,如果我做pointer = new Student[record];会起作用吗?我不知道这是否是您如何将 Student 数组动态分配到与文件中的行数相同的大小。函数参数中的指针让我很困惑。
struct Student
{
string name;
double gpa[NUM_OF_QUARTERS];
double average;
};
bool fillArr(Student* pointer);
int main()
{
Student* ptr;
if (!fillArr(ptr))
return 1;
return 0;
}
bool fillArr(Student* pointer)
{
ifstream infile;
infile.open("student_records.txt");
if (!infile)
{
cout << "Error opening file\n";
return false;
}
int record = 0;
string str;
while(getline(infile, str))
++record;
cout << "number of lines in the file " << record << endl;
infile.clear();
infile.seekg(0, ios::beg);
pointer = new Student[record]; // Is this how you would dynamically allocate the Student array?
// after dynamically allocating Student array, read in the data from the file
}
【问题讨论】: