How can I create a dynamically sized array of structs?

后端 未结 10 1240
春和景丽
春和景丽 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 dynamically allocate arrays, you can use malloc from stdlib.h.

    If you want to allocate an array of 100 elements using your words struct, try the following:

    words* array = (words*)malloc(sizeof(words) * 100);
    

    The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

    The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

    Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

    free(array);
    

    If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

提交回复
热议问题