gpt4 book ai didi

c - 在 C 中为字符串数组动态分配内存

转载 作者:行者123 更新时间:2023-12-04 12:08:38 24 4
gpt4 key购买 nike

我正在尝试使用 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 的过多调用,这可能每次都移动分配的内存。

关于c - 在 C 中为字符串数组动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com