-1

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

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.