[英]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.