如何在C ++中创建动态分配的结构2D数组?

时间:2017-12-13 06:03:08

标签: c++ arrays structure dynamic-allocation

我正在尝试创建2D数组结构并打印该值。如何“Segmentaion fault(core dumped)”消息“。

#include <iostream>
#include <string>
using namespace std;

struct student{
    string name;
    int age;
    float marks;
};
student* initiateStudent(string name, int age, float marks){
    student *studFun;
    studFun->name = name;
    studFun->age = age;
    studFun->marks =  marks;
    return studFun;  

}
int main() {
    int totalStudents = 1;
    string name;
    int age;
    float marks;
    cin >> totalStudents;
    student** stud = new student*[totalStudents];
    for(int i=0;i<totalStudents;i++){
        stud[i] = new student[1];
        cin >> name >> age >> marks;
        stud[i] = initiateStudent(name,age,marks);
    }

    delete [] stud;
    return 0;
}

我正在使用Netbeans for C ++编译它。谁能告诉我这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

这应该有效

#include <iostream>
#include <string>
using namespace std;

struct student{
   string name;
   int age;
   float marks;
};
student* initiateStudent(string name, int age, float marks){
   student *studFun = new student();
   studFun->name = name;
   studFun->age = age;
   studFun->marks =  marks;
   return studFun;
}
int main() {
   int totalStudents = 1;
   string name;
   int age;
   float marks;
   cin >> totalStudents;
   student** stud = new student*[totalStudents];
   for(int i=0;i<totalStudents;i++){
       stud[i] = new student[1];
       cin >> name;
       cin >> age;
       cin >> marks;
       stud[i] = initiateStudent(name,age,marks);
  }

  delete [] stud;
  return 0;
}