簡體   English   中英

分段錯誤,在動態分配的結構內動態分配結構

[英]Segmentation Fault , dynamically allocating a structure inside a dynamically allocated structure

這是我完整的代碼 ..這是一個很大的代碼感謝您的寶貴時間

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM