先从一个大小小的数组开始,然后每当需要增加大小时,都使用realloc它;每次调整大小时,通常都会将数组的大小加倍。
例如:
int length = 5;
my_struct *array = NULL;
/* Initialization */
array = (my_struct *)malloc(length * sizeof(my_struct));
/* Use array[0] .. array[length - 1] */
/* When you reach the limit, resize the array */
length *= 2;
array = (my_struct *)realloc(array, length * sizeof(my_struct));
Run Code Online (Sandbox Code Playgroud)