Increase Array Size
We cannot increase the size of an existing array, the alternative is to create a bigger one and transfer the contents of the smaller one onto it.
int *p = (int *)malloc(5 * sizeof(int));
p = {3, 5, 7, 9, 11};
int *q = (int *)malloc(10 * sizeof(int));
for (i = 0; i < 5; i++)
q[i] = p[i];
free(p);
p = q;
q = NULL;
// p array size is now 10.
There is even a function in C to do that, called memcpy, that is memory copy.
- An array size cannot be grown, because the memory for the array should be contiguous. There is no guarantee that the next consecutive locations after the array are free or not.