如何在结构数组中初始化和动态分配一个 int 指针成员?

How can I initialize and dynamically allocate an int pointer member in an array of structs?

如何初始化和动态分配结构数组中的 int 指针?

我的程序允许我打印 enroll[0].grades[x],但是当我尝试访问除 0 以外的任何其他 enroll 索引值时(例如 enroll[1].grades[x] or enroll[2].grades[x]), 我的程序分段错误.

这是我的代码...

如何让enroll[2].grades[x],例如,初始化并等于零?

在我的结构中:

struct Enroll
{
        int *grades;
};

主要内容:

struct Enroll *enroll = (struct Enroll *) calloc(count.enroll, 10 * sizeof(struct Enroll));

enroll->grades = (int *) calloc(count.grades, 10 * sizeof(int));

在函数中:

enroll[x].grades[y];

主要你应该

struct Enroll *enroll =  calloc(count.enroll, sizeof(struct Enroll));

for(int i = 0; i < count.enroll ;i++)
{
    enroll[i].grades =  calloc(count.grades,  sizeof(int));
}

在您的代码中,您没有为每个整数指针分配内存。

为结构登记数分配内存

struct Enroll *p = calloc(count.enroll, sizeof(struct Enroll));

现在你有要填充的结构数量,你需要的是用于保存值的int指针的内存,int个指针的数量是count.enroll

for(i=0;i<count.enroll;i++)
{
   p[i].grades = calloc(count.grades,sizeof(int)); 
   // Fill in the values
}

PS:或者你可以选择 malloc() 然后是 memset()