【问题标题】:How to dynamically allocate a structure that involves a pointer?如何动态分配涉及指针的结构?
【发布时间】: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
}

【问题讨论】:

    标签: c++ arrays struct


    【解决方案1】:

    您的方法会部分起作用,但我宁愿为此使用std::vector&lt;Student&gt;。如果你想真正花哨,你可以使用std::vector::emplace_back()函数来避免先构造Student,然后用std::vector::push_back()将其复制到std::vector中的开销。您可以找到一个非常好的描述和示例here,它使用President 类型而不是Student

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

    如果将ptr 变量“按值”传递给fillArr(),则main() 中的ptr 不会被更改,因为fillArr() 中的pointer 包含ptr 的值函数调用的时间。函数签名会发生这种情况

    bool fillArr(Student *pointer)
    

    如果您改为“按引用”传递它,fillArr() 中的 pointer 将引用您在 main() 中传递的变量。建议的函数签名会发生这种情况

    bool fillArr(Student *&pointer)
    

    【讨论】:

      【解决方案2】:

      您在此处使用的方法将无法正常工作,因为您是按值传递指针。如果您想以这种方式继续,请更改函数,使其通过引用获取指针:

      bool fillArr(Student*& ptr) {
         ...
      }
      

      如果您不这样做,那么您只会更改原始指针的副本指向的位置,而不是原始指针本身指向的位置。

      也就是说,我认为不使用std::vector 代替动态分配的数组会使事情变得比实际需要的困难得多。使用std::vector 会容易得多:

      std::vector<Student> fillArr() {
          ifstream infile("student_records.txt");
          if (!infile) {
            /* error handling */
          }
      
          std::vector<Student> result;
          for (string line; getline(infile, line); ) {
               Student curr = /* initialize curr based on line */
               result.push_back(curr);
          }
          return result;
      }
      

      这避免了原始指针,只读取文件一次,不会冒提供的指针为空的风险,并且不需要显式内存管理。这更像是 C++ 做事的方式,所以我强烈推荐它!

      【讨论】:

      • 我的老师还没有研究过向量,所以不幸的是我不知道他们做了什么。
      猜你喜欢
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多