Search code examples
c++arraysstructuredynamic-allocation

How to create dynamically allocated 2D array of Structures in C++?


I am trying to create 2D array of structures and print the value. How "Segmentaion fault (core dumped)" message".

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

I am compiling it using Netbeans for C++. Can anyone tell me whats wrong with this code ?


Solution

  • This should work

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