I have to learn memory management in class and how to dynamically allocate memory with the new operator.
I have a struct that is
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
I am trying to fill the member variables with a for loop but I am unsure how to use a getline with courseName. I was able to use a regular cin but it won’t work if the class name has spaces.
Below is my code and what I’ve tried but I get a arguement error that courseArray is undefined.
Course* readCourseArray(int &courses) //Read Courses
{
cout<<"\nHow many courses is the student taking?\n";
cin>>courses;
const int *sizePTR = &courses;
Course *coursePTR = new Course[*sizePTR];
for(int count = 0; count < *sizePTR; count++) //Enter course information
{
cout<<"\nEnter student "<<count+1<<"'s course name\n";
getline(cin,courseArray[count].courseName);
cout<<"\nEnter student "<<count+1<<"'s course number\n";
cin>>coursePTR[count].courseNumber;
cout<<"\nEnter student "<<count+1<<"'s credit hours\n";
cin>>coursePTR[count].creditHours;
cout<<"\nEnter student "<<count+1<<"'s grade\n";
cin>>coursePTR[count].grade;
}
return coursePTR;
}
The pointer to your array is called
coursePTR, notcourseArray. Just replace the namecourseArraywithcoursePTR.For this line:
You don’t have to do that, you can just use
coursesdirectly (so, remove all the*from the places you usesizePTRthen changesizePTRtocourses).Also I hope you are remembering to
delete[]the return value ofreadCourseArray:)