I have spent the past few hours trying to figure out why I am getting a seg-fault. My code runs fine, being that my nameList pointer array is initialized with the names that I enter. However, when I pass nameList to my function to dynamically allocate the right amount of space per name in the createStudentList function. If you have any ideas, please inform me with an explanation, I am not looking only for an answer to fix it. Thank you. (This is an assignment, so some guidelines need to be followed [such as using char arrays instead of strings].)
Here is my code:
#include "main.h"
using namespace std;
const int MAXCHAR = 101;
struct Student
{
char *name;
double gpa;
};
Student ** createStudentList(char ** names, int size);
int main()
{
int size = 0;
char temp[MAXCHAR];
char **nameList = nullptr;
Student **studentList = nullptr;
cout << "Enter amount of names: ";
cin >> size;
cout << endl;
cin.clear();
cin.ignore(10, '\n');
nameList = new char *[size];
for(auto i = 0; i < size; i++)
{
cout << "Enter name: ";
cin.get(temp, MAXCHAR, '\n');
cout << endl;
cin.ignore(10, '\n');
nameList[i] = new char[strlen(temp) + 1];
strcpy(nameList[i], temp);
}
studentList = createStudentList(nameList, size);
return 0;
}
Student ** createStudentList(char ** names, int size)
{
Student **tempStudentList = nullptr;
tempStudentList = new Student *[size];
for(auto idx = 0; idx < size; idx++)
{
tempStudentList[idx]->name = new char[strlen(names[idx]) + 1];
strcpy(tempStudentList[idx]->name, names[idx]);
tempStudentList[idx]->gpa = 0;
}
return tempStudentList;
}