任务是创建一个结构数组,其中包含10个作为“学生”的元素,每个元素都有一个得分和一个ID。我不允许更改代码中的某些内容(例如main中的任何内容)。
#include <stdio.h>
#include <stdlib.h>
struct student* allocate(){
struct student* array = malloc(10 * sizeof(struct student));
return array;
}
void deallocate(struct student* stud){
int i = 0;
for(;i<10;i++)
free(&stud[i]);
}
因此,这可以正常编译,其余代码可以正常运行,但是当内核到达free()时,内核将转储。另外,这是我的教授给我的主要内容,告诉我不要改变。没有调用deallocate函数,所以现在我想知道main完成后是否会自动调用它,或者他是否错误地遗漏了它。我添加了它,因为我认为这是合理的。
int main(){
struct student* stud = allocate();
generate(stud);
output(stud);
sort(stud);
for(int i=0;i<10;i++){
printf("%d %d\n", stud[i].id,stud[i].score);
}
printf("Avg: %f \n", avg(stud));
printf("Min: %d \n", min(stud));
deallocate(stud);
return 0;
}
最佳答案
通过1个(m)allocated
调用将10个学生数组作为1个连续的内存块(这是正确的)。
要释放它,您只能在第一个数组元素上使用malloc
一次。这将释放整个连续的内存块,即整个10个学生的数组。
关于c - C从结构数组释放内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39797660/