【问题标题】:Dynamically Allocate Memory for String Array in C在 C 中为字符串数组动态分配内存
【发布时间】: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 倍。之后你可以简单地重新分配(向下)。

标签: c arrays string


【解决方案1】:

您可以使用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 的过度调用,这可能每次都会移动分配的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2016-09-29
    • 2018-06-16
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2014-12-09
    相关资源
    最近更新 更多