【发布时间】:2018-04-07 18:49:57
【问题描述】:
这是我的完整代码....这是一个很大的代码,感谢您的宝贵时间。
在上面的代码中,我想知道为什么我无法为结构中的结构动态分配内存的确切原因。我通常参加 codechef、hackerrank、codeforces。但是,我是做这些项目的新手......我已经调试了一点,所以我发现了错误在哪里,但我无法纠正它,我无法安然入睡......如果你发现原因请告诉我并帮助我解决它 !!
简而言之,我的代码是为那些没有多少空闲时间的人准备的 :) :-
struct subject
{
struct DateTime StartTime,EndTime; //Don't bother about these structure definitions
string ClassName,ClassType;
int ThresholdPercentage,MaxPossiblePercentage;
struct Note notes; //Don't bother about these structure definitions
};
struct students
{
struct subject *subjects;
string name;
int MaxSubjects;
} *student;
int main(void)
{
int NStudents,Subjects,i,j;
cout<<"Enter Number of Students:- ";
cin>>NStudents;
student=(struct students*)malloc(sizeof(struct students)*(NStudents+1));
cout<<'\n';
for(i=1;i<=NStudents;i++)
{
cout<<"Enter Number of Subjects for "<<i<<" Student:- ";
cin>>Subjects;
student[i].MaxSubjects=Subjects;
student[i].subjects=(struct subject*)malloc(sizeof(struct subject)*(Subjects+1));
cout<<'\n';
for(j=1;j<=Subjects;j++)
{
cout<<"Enter the name of Subject "<<j<<" :- ";
cin>>student[i].subjects[j].ClassName;//<<<==================FAULT HERE.
}
PrintStudentSubjects(i);
}
return 0;
}
实际问题
struct subject
{
struct DateTime StartTime,EndTime; //Don't bother about these structure definitions
string ClassName,ClassType;
int ThresholdPercentage,MaxPossiblePercentage;
struct Note notes; //Don't bother about these structure definitions
};
struct students
{
struct subject *subjects;
string name;
int MaxSubjects;
} *student;
student=(struct students*)malloc(sizeof(struct students)*(NStudents+1));
student[i].subjects=(struct subject*)malloc(sizeof(struct subject)*(Subjects+1));//<<== In a loop..
这给了我一个分段错误...我不能使用 malloc 吗?,如果不是为什么?..如果是,如何启发我 :) .
【问题讨论】:
-
不要使用 malloc。不要使用原始指针。相反,使用
std::vector<student>,它有一个成员std::vector<subject>。 -
编辑您的问题以包含minimal reproducible example。
-
你应该索引你的数组从 0 到 n-1,而不是从 1 到 n。
-
不,C++ 中的
malloc不起作用。 (除非您是专家并且真的知道自己在做什么。) -
malloc是一个 C 库函数,它对 C++ 构造函数一无所知。std::string成员变量未正确初始化,然后当您尝试使用它们时您的代码崩溃。我将成为 cmets 中第三个说不要使用malloc的人。
标签: c++ segmentation-fault structure project dynamic-memory-allocation