【发布时间】:2018-08-29 01:14:14
【问题描述】:
我正在尝试使用 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 *));
【问题讨论】:
-
你可以做你的第二件事 -
malloc(i *...。第一个是非标准的c扩展(变长数组) -
查找
realloc。 -
4k(或 64 位系统上的 8k)不会破产。我想说你已经在这里浪费了足够多的时间。但如果你打算用 C 语言编写代码,你应该了解
realloc。 -
@rici 我同意我在这里所拥有的可能毫无意义,而且我现在拥有的代码很好,我只是发布了它,因为我找不到答案,所以现在会有一个供其他人使用处于类似情况的人。
-
只有 sizeof(char *) 的 1024 倍。之后你可以简单地重新分配(向下)。