我对 C 语言相当陌生,并且在弄清楚如何将连续内存分配给结构数组时遇到了麻烦。在这个作业中,我们得到了一个代码的外壳,并且必须填写其余部分。因此,我无法更改变量名称或函数原型。这是给我的:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct student {
int id;
int score;
};
struct student *allocate() {
/* Allocate memory for ten students */
/* return the pointer */
}
int main() {
struct student *stud = allocate();
return 0;
}
我只是不确定如何按照分配函数中的这些评论进行操作。
分配和初始化数组的最简单方法是:
struct student *allocate(void) {
/* Allocate and initialize memory for ten students */
return calloc(10, sizeof(struct student));
}
笔记:
-
calloc()
,不像malloc()
将内存块初始化为所有位零。因此,数组中所有元素的字段id
和score
都初始化为0
。
将 - 学生人数作为参数传递给函数
allocate()
是个好主意。 - 当您不再需要分配的内存时,
free()
它被认为是一种很好的风格。您的讲师没有暗示您应该在从main()
返回之前调用free(stud);
:虽然不是绝对必要的(程序分配的所有内存在程序退出时由系统回收),但这是一个好习惯,可以更轻松地在较大的程序中定位内存泄漏。