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

时间:2018-08-29 01:14:14

标签: c arrays string

我试图用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 *));

1 个答案:

答案 0 :(得分:2)

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