![](/img/trans.png)
[英]Segmentation fault with dynamically allocated arrays as members of structure in c++?
[英]Segmentation Fault , dynamically allocating a structure inside a dynamically allocated structure
這是我完整的代碼 ..這是一個很大的代碼 , 感謝您的寶貴時間 。
在上面的代碼中,我想知道為什么我無法為結構內的結構動態分配內存的確切原因。我通常在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.