[英]Dynamically Allocate Memory for String Array in C
我試圖在C系列的字符串數組中存儲Linux系統上每個掛載點的列表。我專注於這段代碼。
int i = 0;
char **mountslist = malloc(1024 * sizeof(char *));
/*
* Make sure that the number entries in the array are less than the allocated
* 1024 in the absurd case that the system has that many mount points.
*/
while (i < 1024 && (ent = getmntent(mounts))) {
/*
* The output of getmntent(mounts) goes down to
* the next mount point every time it is called.
*/
mountslist[i] = strdup(ent->mnt_dir);
i++;
}
我想知道如何動態分配mountslist
數組中的條目數(當前靜態設置為1024)以避免該限制並浪費內存。 如果我在聲明mountslist
時得到了i
的最終值,我可以使用char *mountslist[i];
或者char **mountslist = malloc(i * sizeof(char *));
您可以使用realloc
更改已分配內存塊的大小:
int i = 0;
int len = 10;
char **mountslist = malloc(len * sizeof(char *));
while ((ent = getmntent(mounts)) != NULL) {
if (i >= len) {
len *= 2;
char **tmp = realloc(mountslist, len * sizeof(char *));
if (tmp) {
mountslist = tmp;
}
}
mountslist[i] = strdup(ent->mnt_dir);
i++;
}
如上所示,一個好的規則是在空間不足時分配的空間量加倍。 這可以防止過多調用realloc
,這可能每次都會移動分配的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.