繁体   English   中英

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

[英]How to dynamically allocate memory for an array of structs

我对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()不同,将内存块初始化为所有零位。 因此,将数组中所有元素的字段idscore初始化为0
  • 将学生人数作为参数传递给函数allocate()是一个好主意。
  • 当您不再需要free()分配的内存时,这是一种很好的样式。 您的老师没有暗示您应该拨打free(stud);电话free(stud); main()返回之前:尽管不是绝对必要的(程序退出时,程序分配的所有内存都会被系统回收),但是这是一个好习惯,可以使较大程序中的内存泄漏更容易找到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM