这是我完整的代码 ....这是一个很大的代码,感谢您的宝贵时间

https://pastebin.com/Uj97g357

在上面的代码中,我想知道为什么我无法为结构内的结构动态分配内存的确切原因。我通常在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..

这给了我一个Segmentation Fault ...我不能使用malloc吗?,如果不是为什么呢?如果是的话,如何启发我:)。

最佳答案

malloc()不会为您的类调用构造函数。使用new

student = new students[NStudents+1];
student[i].subjects = new subject[Subjects+1];

关于c++ - 段错误,在动态分配的结构内动态分配结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49710810/

10-13 06:58
查看更多