Since the size is unknown in the beginning, allocating the space for the size of one more element is inefficient.
One possible solution is: reallocate the space(Use realloc
) twice the size of the previous size whenever the size is not enough.
Real size - Space size
0 0
1 1
2 2
3 4
4 4
5 8
6 8
7 8
8 8
9 16
10 16
... ...
This way, the times of reallocation is not much, and you don't waste much space.