如何为结构数组动态分配内存
How to dynamically allocate memory for an array of structs
我是 C 的新手,并且无法弄清楚如何将连续内存分配给结构数组。在这个作业中,我们给出了一个 shell 的代码,并且必须填写其余部分。因此,我无法更改变量名或函数原型。这是给我的:
#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);
:虽然不是绝对必要的(程序分配的所有内存在程序退出时由系统回收),但这是一个好习惯采取并更容易定位大型程序中的内存泄漏。
我是 C 的新手,并且无法弄清楚如何将连续内存分配给结构数组。在这个作业中,我们给出了一个 shell 的代码,并且必须填写其余部分。因此,我无法更改变量名或函数原型。这是给我的:
#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);
:虽然不是绝对必要的(程序分配的所有内存在程序退出时由系统回收),但这是一个好习惯采取并更容易定位大型程序中的内存泄漏。