释放动态struct数组的内存

时间:2017-01-19 19:11:07

标签: c struct dynamic-memory-allocation

再次对我说:D

我有以下结构:

typedef struct
{
    int day, month, year;
}date;

typedef struct
{
    char name[15];
    date birth;
    int courses;
    int *grades;
}student;

这就是我如何为每个阵列分配内存:

printf("What is the number of students?\n");
    scanf("%d", &size); //asking for size from user and creating 'size' number of structs
    for (i = 0; i < size; i++) {
        pData[i] = malloc(sizeof(student) * size);
    }
    ........ //initializing char and birth
    for (i = 0; i < size; i++) {
        printf("\nPlease enter number of courses of student #%d:\n", i+1);
        scanf("%d", &pData[i]->courses); //allocating memory for array of grades for each student (i)
        pData[i]->grades = (int*)malloc(sizeof(int)*pData[i]->courses);
    }
    for (j = 0; j < size; j++) {
        for (i = 0; i < pData[j]->courses; i++) {
            printf("\nPlease enter grades of student #%d in course #%d\n", j+1, i+1);
            scanf("%d", &pData[j]->grades[i]);
        } //entering grades of each student

现在我有麻烦释放内存......我尝试了很多方法,但程序每次都以错误结束..

我尝试过这种方法:

for (i = 0; i < size; i++) {
        free(pData[i].grades);
    }
    free(pData);
    pData = NULL;

然而我仍然有错误......

编辑:这就是我在可靠的pData上声明的方式:

student* pData = NULL;

这是初始化数组的函数:

int initialize(student**);

这就是我如何将pData发送到函数:

size = initialize(&pData); //the function is suppose to return the size of the array.

1 个答案:

答案 0 :(得分:0)

您没有正确地为pData分配空间。您这样做一次并将其分配给*pData,而不是pData[i]。你有一个指向指针的指针,而不是一个指针数组。

printf("What is the number of students?\n");
scanf("%d", &size); //asking for size from user and creating 'size' number of structs
*pData = malloc(sizeof(student) * size);

然后,您需要在读取数据时正确引用它。

for (i = 0; i < size; i++) {
    printf("\nPlease enter number of courses of student #%d:\n", i+1);
    scanf("%d", &(*pData)[i].courses); //allocating memory for array of grades for each student (i)
    (*pData)[i].grades = (int*)malloc(sizeof(int)*(*pData)[i].courses);
}
for (j = 0; j < size; j++) {
    for (i = 0; i < (*pData)[j].courses; i++) {
        printf("\nPlease enter grades of student #%d in course #%d\n", j+1, i+1);
        scanf("%d", &(*pData)[j].grades[i]);
    } 
}

编辑:

为了进一步解释如何使用pData的语法,以下是相关表达式各部分的数据类型。

         pData:   student **
        *pData:   student *
   (*pData)[i]:   student