创建结构元素的动态数组,然后创建该结构的动态数组.C++

Creating a dynamic array of a structure element then creating a dynamic array of the structure. C++

本文关键字:创建 数组 动态 结构 C++ 元素 然后      更新时间:2023-10-16

我试图创建一个学生结构,然后在该结构中有一个基于用户输入的分数(或分数)数组。

然后我尝试创建一个学生结构的动态数组。

我想与这些指针互动,即输入学生信息和成绩,然后对它们进行排序,但我认为我做得不好。这是我的代码开头的一段。我的主要问题是创建一个标记数组,我在课本上找不到如何声明它

#include <string.h>
#include <iostream>
#include <sstream>
using namespace std;

struct Student
{
  string name;
  int id;
  int* mark;
  ~Student()
 {
   delete [] mark;
   mark = NULL;
 };
};
void initStudent(Student* ptr, int markNum, int studentNum );   // function prototype for initialization
void sayStudent(Student* ptr, int markNum, int studentNum);     // function prototype for printing
//*********************** Main Function ************************//
int main ()
{
  int marks, studentNum;
  Student stu;           // instantiating an STUDENT object
  Student*  stuPtr = &stu;  // defining a pointer for the object
  cout << "How many marks are there? ";
  cin >>  marks;
  cout << "How many students are there?";
  cin >> studentNum;
  Student* mark = new int[marks];
  Student* students = new Student[studentNum];
  initStudent(students,marks,studentNum);      // initializing the object
  sayStudent(students,marks,studentNum);       // printing the object
  delete [] students;
return 0;
} // end main
//-----------------Start of functions----------------------------//
void initStudent(Student* ptr, int markNum, int studentNum)
{
    for (int i = 0; i < studentNum; i++)
    {
       cout << "Enter Student " << i+1 << " Name :";
       cin >> ptr[i].name;
       cout << "Enter Student ID Number :";
       cin >> ptr[i].id;
       for (int j = 0; j < markNum; j++)
        {
       cout << "Please enter a mark :";
       cin >> ptr[i].mark[j];
        }
     }
  }

您需要在每个Student元素中分配marks数组。

Student* students = new Student[studentNum];
for (int i = 0; i < studentNum; i++) {
    students[i].mark = new int[marks];
}

您也可以在initStudent中执行此操作。

void initStudent(Student* ptr, int markNum, int studentNum)
{
    for (int i = 0; i < studentNum; i++)
    {
       cout << "Enter Student " << i+1 << " Name :";
       cin >> ptr[i].name;
       cout << "Enter Student ID Number :";
       cin >> ptr[i].id;
       ptr[i].mark = new int[markNum]
       for (int j = 0; j < markNum; j++)
        {
            cout << "Please enter a mark :";
            cin >> ptr[i].mark[j];
        }
     }
  }