Here is an example showing one way to manage a dynamic array.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* To manage an array of varying size, we keep a pointer to the first
element of the array and the number of elements in the array.
The pointer is initially null, and there are no elements in the array.
*/
int *Numbers = NULL;
size_t NumberOfAllocatedElements = 0;
/* We get numbers one by one, using TemporaryNumber to hold them. As long
as scanf reports it was able to read and assign 1 item, we continue
adding the number to the array.
*/
int TemporaryNumber;
while (1 == scanf("%d", &TemporaryNumber))
{
/* To grow the array, increase the number of allocated elements and
use realloc to request more space.
*/
int *NewNumbers =
realloc(Numbers, ++NumberOfAllocatedElements * sizeof *NewNumbers);
/* If realloc fails, we report an error and exit. A more
sophisticated program could do something else in this case.
*/
if (!NewNumbers)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// Update our pointer with the new address.
Numbers = NewNumbers;
// Record the new element in the array.
Numbers[NumberOfAllocatedElements - 1] = TemporaryNumber;
}
// Show the contents of the array.
for (size_t i = 0; i < NumberOfAllocatedElements; ++i)
printf("Number %zu is %d.\n", i, Numbers[i]);
// Release the memory.
free(Numbers);
}
This is largely a beginner example. An improvement would be to allocate large amounts of memory at a time, instead of just one more element each time. In this case, the program then needs to track two numbers about the array: The amount of space allocated and the number of elements currently used in it.
A variety of alternatives are also possible.