簡體   English   中英

釋放動態struct數組的內存

[英]Freeing memory of dynamic struct array

它又來了我: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.

你沒有正確地為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

暫無
暫無

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

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