How can I create a dynamically sized array of structs?

后端 未结 10 1233
春和景丽
春和景丽 2020-11-27 11:46

I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?

<
10条回答
  •  伪装坚强ぢ
    2020-11-27 12:31

    If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

    Some example code would be:

    size = 64; i = 0;
    x = malloc(sizeof(words)*size); /* enough space for 64 words */
    while (read_words()) {
        if (++i > size) {
            size *= 2;
            x = realloc(sizeof(words) * size);
        }
    }
    /* done with x */
    free(x);
    

提交回复
热议问题