我正在尝试使用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
函数。 - user253751