在过去的几个小时里,我一直在努力弄清楚为什么会出现段错误。我的代码运行良好,因为我的 nameList 指针数组是用我输入的名称初始化的。但是,当我将 nameList 传递给我的函数以在 createStudentList 函数中为每个名称动态分配适当的空间量时。如果您有任何想法,请通过解释通知我,我不只是在寻找解决问题的答案。谢谢。 (这是一项任务,因此需要遵循一些准则 [例如使用字符数组而不是字符串]。)
这是我的代码:
#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;
}
最佳答案
您没有在循环中分配 Student
实例。试试这个:
for(auto idx = 0; idx < size; idx++)
{
tempStudentList[idx] = new Student;
tempStudentList[idx]->name = new char[strlen(names[idx]) + 1];
strcpy(tempStudentList[idx]->name, names[idx]);
tempStudentList[idx]->gpa = 0;
}
此外,正如评论中所指出的,这不是现代 C++。您最好使用 std::string
和 std::vector
。例如,将 Student
更改为:
struct Student
{
std::string name;
double gpa;
};
在createStudentList
中添加使用std::vector
:
std::vector<Student> createStudentList(const std::vector<string> &names)
{
std::vector<Student> students;
for(auto idx = 0; idx < names.size(); idx++)
{
Student student;
student.name = names[index];
student.gpa = 0
students.push_back(student);
}
return students;
}
这将使您不必分配原本需要删除的原始内存。
关于c++ - 指针数组分配的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339996/