【问题标题】:How do you create a dynamic array for struct elements of different variable types for c++?如何为 c++ 的不同变量类型的结构元素创建动态数组?
【发布时间】:2020-02-13 04:42:26
【问题描述】:

我有以下结构:

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

其余代码在 main 函数中。 我询问用户一个班级有多少学生并将其存储在 numStudents 中:

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

现在我必须创建一个动态数组来存储 numStudents 的姓名,并要求用户输入之前输入的学生人数的姓名和考试成绩。这是我到目前为止的代码。辛工作。但是当我尝试输出时,系统就退出了。

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

【问题讨论】:

    标签: c++ dynamic-memory-allocation


    【解决方案1】:

    ptr 是数组而不是 ptr.name ... 您实际上正在做的是将数组中第一项的属性视为数组。但事实并非如此。 您应该将其更改为:

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

    您还可以在answer 中阅读有关此错误消息的更多信息

    【讨论】:

    • 我这样做了,但它不会让我输出代码并且没有完成就退出。输出格式是否相同?像 cout
    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 2021-09-25
    • 2015-11-30
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多