[英]How to dynamically allocate memory for an array of structs
I am fairly new to C, and am having trouble figuring out how to allocate contiguous memory to an array of structs. 我对C相当陌生,并且在弄清楚如何将连续内存分配给结构数组时遇到麻烦。 In this assignment, we are given a shell of the code, and have to fill in the rest. 在此分配中,我们获得了代码的外壳,并且必须填写其余部分。 Thus, I cannot change the variable names or function prototypes. 因此,我无法更改变量名称或函数原型。 This is what has been given to me: 这是给我的:
#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;
}
I'm just not sure how to go about doing what those comments say in the allocate function. 我只是不确定如何去做那些评论在分配功能。
The simplest way to allocate and initialize the array is this: 分配和初始化数组的最简单方法是:
struct student *allocate(void) {
/* Allocate and initialize memory for ten students */
return calloc(10, sizeof(struct student));
}
Notes: 笔记:
calloc()
, unlike malloc()
initializes the memory block to all bits zero. calloc()
与malloc()
不同,将内存块初始化为所有零位。 Hence the fields id
and score
of all elements in the array are initialized to 0
. 因此,将数组中所有元素的字段id
和score
初始化为0
。 allocate()
. 将学生人数作为参数传递给函数allocate()
是一个好主意。 free()
allocated memory when you no longer need it. 当您不再需要free()
分配的内存时,这是一种很好的样式。 Your instructor did not hint that you should call free(stud);
您的老师没有暗示您应该拨打free(stud);
电话free(stud);
before returning from main()
: while not strictly necessary (all memory allocated by the program is reclaimed by the system when the program exits), it is a good habit to take and makes it easier to locate memory leaks in larger programs. 从main()
返回之前:尽管不是绝对必要的(程序退出时,程序分配的所有内存都会被系统回收),但是这是一个好习惯,可以使较大程序中的内存泄漏更容易找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.