创建结构元素的动态数组,然后创建该结构的动态数组.C++
Creating a dynamic array of a structure element then creating a dynamic array of the structure. C++
我试图创建一个学生结构,然后在该结构中有一个基于用户输入的分数(或分数)数组。
然后我尝试创建一个学生结构的动态数组。
我想与这些指针互动,即输入学生信息和成绩,然后对它们进行排序,但我认为我做得不好。这是我的代码开头的一段。我的主要问题是创建一个标记数组,我在课本上找不到如何声明它
#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];
}
}
}
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?