我的c ++程序在接收用户输入时崩溃

时间:2018-03-19 18:23:41

标签: c++ arrays struct crash

我正在尝试制作一个程序,从用户那里获取学生的姓名,号码和主题代码。然而,当它获得主题代码(应该是一个字符串数组)时,程序崩溃了。我在这做错了什么?

#include <string>
#include <stdlib.h>
#include <iostream>

using namespace std;

typedef struct Student {
    string student_number;
    string student_name;
    string* student_codes;

}Student;

void GetStudent(Student* student) {
    int num;
    int numOfSubjects;
    cout<<"enter the number of students:\n";
    cin >> num;
    student = (Student*)malloc(num * sizeof(Student));
    for (int i = 0; i < num; i++) {
        cout<< "enter student "<<i+1<< "'s name\n";
        cin >> student[i].student_name;
        cout<< "enter student "<<i+1<< "'s number\n";
        cin >> student[i].student_number;
        cout<< "enter the number of subjects:\n";
        cin >> numOfSubjects;
        student->student_codes = (string*)malloc(numOfSubjects * 
sizeof(string));
        for (int j = 0; j < numOfSubjects; j++) {
            cout<< "enter sunject "<<j+1<< "'s code\n";
            cin >> student[i].student_codes[j];
        }

    }
}


int main()
{
    Student student;
    GetStudent(&student);
    return 0;
}

0 个答案:

没有答案