如何为结构数组动态分配内存

Con*_*n97 1 c arrays struct memory-management contiguous

我对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;
}
Run Code Online (Sandbox Code Playgroud)

我只是不确定如何去做那些评论在分配功能中所说的内容.

chq*_*lie 6

分配和初始化数组的最简单方法是:

struct student *allocate(void) {
    /* Allocate and initialize memory for ten students */
    return calloc(10, sizeof(struct student));
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • calloc(),不像malloc()将内存块初始化为所有位零.因此,数组中的字段idscore所有元素都被初始化为0.
  • 将学生数量作为参数传递给函数是个好主意allocate().
  • free()当您不再需要它时,它被认为是分配内存的好方式.你的教练没有暗示你应该free(stud);在返回之前调用main():虽然不是绝对必要的(当程序退出时,程序分配的所有内存都由系统回收),这是一个很好的习惯,可以更容易地找到内存泄漏在较大的节目中.