【问题标题】:Creating a dynamic array of a structure element then creating a dynamic array of the structure. C++创建结构元素的动态数组,然后创建结构的动态数组。 C++
【发布时间】:2016-04-15 23:25:20
【问题描述】:

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

然后,我尝试创建 Student 结构的动态数组。

我想与这些指针交互,即输入学生信息和成绩,然后计算它们,但我认为我没有正确执行此操作。这是我的代码开头的一段。我的主要问题是创建一系列标记,我在教科书中找不到如何声明它。

#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];
        }
     }
  }

【问题讨论】:

  • 我在教科书中找不到如何声明它。 -- std::vector&lt;int&gt; std::vector&lt;Student&gt; -- 再找一本教科书。
  • @PaulMcKenzie 我需要动态分配内存。不只是创建一个向量。
  • @RoyGunderson “我需要动态分配内存。”你认为std::vector实际上做了什么?
  • 我可以建议Student中的构造函数而不是initStudent吗?
  • @RoyGunderson 然后我尝试创建一个 Student 结构的动态数组 -- C++ 中的动态数组是std::vector

标签: c++ arrays dynamic nested


【解决方案1】:

您需要在每个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];
        }
     }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多