1
其我再次: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;
然而,我仍然得到错误...
编辑:那我就veriable的pData如何声明:
student* pData = NULL;
那是初始化函数阵列:
int initialize(student**);
多数民众赞成我是如何发送pData功能:
size = initialize(&pData); //the function is suppose to return the size of the array.
其不工作,它说 “表达必须有指针类型” 的行(* pData所)[I] - >等级=(INT *)malloc的(的sizeof(int)的*(* pData所)[I ] - >课程); –
@MatanBenishty您在作业左侧的'pData'之前错过了'*'。 – dbush
对不起,我复制它错了,我有*之前的Pdata它没有工作,它给出了错误(如果我删除*它没有给出该错误) –