簡體   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