我试图用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),以避免该限制并浪费内存。如果在声明i
时具有最终值mountslist
,则可以使用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
的过多调用,每次调用都会移动分配的内存。