又是我: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
正确分配空间。这样做一次并将其分配给*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
关于c - 释放动态结构数组的内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41749810/