'Code exiting when Dynamic Array of class allocated

I am trying to dynamically allocate an array and whenever it gets to the part where it dynamically allocates the program exits. I would rather not use vectors as I am trying to learn how to do this using dynamic arrays.

This is the simplified code:

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

class Student
{
private:
double calcAverage(double* testArray);
char calcGrade(double average);
public:
int nTests, sameTests, idNum;
string name;
double average, *testArray;
char grade;
};
int i;

Student fillStudentArray(int nStudents);

int main()
{
*studentArray = fillStudentArray(nStudents);
return 0;
}

Student fillStudentArray(int nStudents)
{
Student *newStudentArray = new Student[nStudents];
cout << "If you can see this I worked. ";
delete[] studentArray;
return *newStudentArray;
}

I have tried the solution posted here Creation of Dynamic Array of Dynamic Objects in C++ but it also exits in a similar way. The main for the code looks like this.

int main()
{
int nStudents = 3; //this number is just for testing, in actual code it has user input
Student** studentArray = new Student*[nStudents];
cout << "1 ";
for(i = 0; i < nStudents; i++)
{
    cout << "2 ";
    studentArray[i] = new Student[25];
    cout << "3 ";
}
return 0;
}


Solution 1:[1]

close (heres a cigar anyway)

Student* fillStudentArray(int nStudents); <<== function must return pointer to students

int main()
{
    int nStudents = 3; <<<=== declared nstudents
    Student *studentArray = fillStudentArray(nStudents); <<< declare studentArray
    return 0;
}

Student *fillStudentArray(int nStudents) <<<== return pointer
{
    Student* newStudentArray = new Student[nStudents];
    cout << "If you can see this I worked. ";
   // delete[] studentArray; <<<== what were you trying to delete?
    return newStudentArray; <<<=== return pointer
}

the second code you showed is not relevant, its creating a 2d array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pm100