简体   繁体   English

如何为 C++ 的不同变量类型的结构元素创建动态数组?

[英]How do you create a dynamic array for struct elements of different variable types for c++?

I have the following struct:我有以下结构:

struct student {
   char *firstName;
   int exam1;
};

The rest of the code is in the main function.其余代码在主函数中。 I ask the user for how many students they have in a class and store that in numStudents:我询问用户他们在一个班级中有多少学生并将其存储在 numStudents 中:

int numStudents;
cout << "How many students do you have in your class? ";
cin >> numStudents;

Now I have to create a dynamic array to store the name of numStudents, and ask the user to input the name and exam score for the number of students entered earlier.现在我必须创建一个动态数组来存储 numStudents 的名称,并要求用户输入之前输入的学生人数的姓名和考试分数。 This is the code I have so far.这是我到目前为止的代码。 Cin works.辛工作。 But when I try to output, the system just exits.但是当我尝试输出时,系统就退出了。

student *ptr = new student[numStudents];

cout << "Enter name, exam1 for each student: ";
for(i = 0; i < numStudents; i++)
{
    cin >> ptr[i].name;
    cin >> ptr[i].exam1;
}
for(i = 0; i < numStudents; i++)
    {
        cout << ptr[i].name;
        cout << ptr[i].exam1;
    }

ptr is the array and not ptr.name ... What you are actually doing is treating the properties of the first item in the array as if they were the arrays .but it's not the case . ptr 是数组而不是 ptr.name ......您实际上正在做的是将数组中第一项的属性视为数组。但事实并非如此。 You should change it to :您应该将其更改为:

student *ptr = new student[numStudents]; 
cout << "Enter name, exam1 for each student: "; 
for(i = 0; i < numStudents; i++) 
{ 
    cin >> ptr[i]->name; 
    cin >> ptr[i]->exam1; 
}

You can also read more about this error message in this answer您还可以在此答案中阅读有关此错误消息的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM