c++ - 段错误,在动态分配的结构中动态分配结构

标签 c++ segmentation-fault structure project dynamic-memory-allocation

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

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..

这给了我一个段错误...我不能使用 malloc 吗?如果不能,为什么?..如果是,怎么来启发我 :)。

最佳答案

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

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

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

相关文章:

c++ - 命名空间范围的构造函数定义是否需要类限定标识符?

Visual Studio 中的 C++ 文件扩展名

c - 指针:表达式不可赋值

C++ - 如何写入和读取包含对象的结构? (写入和读取二进制文件)

c++ - vector<char> 到字符串段错误

python - 内存递归与迭代的大 O 表示法是否相同?

c - 在用 C 编写的 DL 列表中出现段错误?

c++ - 对象在构造函数之后不存在?

c - OpenCL clEnqueueReadBuffer 段错误随机

javascript - 使用 Backbone.js 和 Express.js 构建应用程序