【发布时间】:2017-06-04 15:00:39
【问题描述】:
又是我 :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.
【问题讨论】:
标签: c struct dynamic-memory-allocation