简体   繁体   English

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

[英]Dynamically Allocate Memory for String Array in C

I'm trying to store a list of every mount point on a Linux system in a string array with C. I'm focused on this piece of code. 我试图在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++;
}

I was wondering how I could dynamically allocate the number of entries in the mountslist array (currently statically set at 1024) to avoid that limit and wasting memory. 我想知道如何动态分配mountslist数组中的条目数(当前静态设置为1024)以避免该限制并浪费内存。 If I had the final value of i when declaring mountslist I could use char *mountslist[i]; 如果我在声明mountslist时得到了i的最终值,我可以使用char *mountslist[i]; or char **mountslist = malloc(i * sizeof(char *)); 或者char **mountslist = malloc(i * sizeof(char *));

You can use realloc to change the size of an allocated memory block: 您可以使用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++;
}

As shown above, a good rule is to double the amount of space you allocate when you run out of space. 如上所示,一个好的规则是在空间不足时分配的空间量加倍。 That prevents excessive calls to realloc which may move the allocated memory each time. 这可以防止过多调用realloc ,这可能每次都会移动分配的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM