[英]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()
不同,將內存塊初始化為所有零位。 因此,將數組中所有元素的字段id
和score
初始化為0
。 allocate()
是一個好主意。 free()
分配的內存時,這是一種很好的樣式。 您的老師沒有暗示您應該撥打free(stud);
電話free(stud);
從main()
返回之前:盡管不是絕對必要的(程序退出時,程序分配的所有內存都會被系統回收),但是這是一個好習慣,可以使較大程序中的內存泄漏更容易找到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.