【发布时间】:2016-05-20 07:01:01
【问题描述】:
过去几个小时我一直在试图弄清楚为什么会出现段错误。我的代码运行良好,因为我的 nameList 指针数组是用我输入的名称初始化的。但是,当我将 nameList 传递给我的函数以在 createStudentList 函数中为每个名称动态分配适量的空间时。如果您有任何想法,请告诉我一个解释,我不只是在寻找解决它的答案。谢谢你。 (这是一个赋值,所以需要遵循一些准则[例如使用 char 数组而不是字符串]。)
这是我的代码:
#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;
}
【问题讨论】:
-
这不是现代 C++,使用标准库中的向量和字符串。你不应该依赖原始指针。
-
请给我们看一个导致seg fault的案例
-
@tomekpe 我愿意,但我必须遵守作业的指导方针。我正在学习 C++ 课程,并且需要这样做。对不起
-
@tomekpe:100% 正确。但是,这是一项任务,OP 有特定的限制
-
@HumamHelfawi 不确定你的意思,但这就是 gdb 告诉我的。我输入了两个名字(Ryan 和 Ben),然后尝试将 nameList 传递给函数。程序收到信号 SIGSEGV,分段错误。 0x0000000000400e2c in createStudentList (names=0x614c20, size=2) at main.cpp:52 52 tempStudentList[idx]->name = new char[strlen(names[idx]) + 1];
标签: c++ function pointers struct segmentation-fault