gpt4 book ai didi

c++ - 如何动态分配涉及指针的结构?

转载 作者:行者123 更新时间:2023-11-27 22:53:49 25 4
gpt4 key购买 nike

我正在使用包含三个字段的 Student 结构。然后我在 main 中声明一个指向 Student 结构的指针。然后我将该指针传递给一个函数。此函数计算文件中有多少行,然后动态分配 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
}

最佳答案

您的方法部分可行,但我宁愿使用 std::vector<Student>为了那个原因。如果你真的想花哨,你可以使用 std::vector::emplace_back()函数以避免构建 Student 的开销首先,然后将其复制到 std::vector 中与 std::vector::push_back() .您可以找到非常好的描述和示例 here ,它使用类型 President而不是 Student .

签名应该是bool fillArr(Student *&pointer)如果你想在 main() 中使用新创建的数组.

如果你通过 ptr变量“按值”到 fillArr() , ptrmain()不会改变,因为pointerfillArr()包含 ptr 的值在函数调用时。这发生在函数签名上

bool fillArr(Student *pointer)

如果您改为“通过引用”传递它,pointerfillArr()将引用您在 main() 中传递的变量.这发生在建议的函数签名中

bool fillArr(Student *&pointer)

关于c++ - 如何动态分配涉及指针的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096697/

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