how to make a dynamic array in c code example
Example 1: C dynamic array
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
Example 2: C dynamic array
Array a;
int i;
initArray(&a, 5);
for (i = 0; i < 100; i++)
insertArray(&a, i);
printf("%d\n", a.array[9]);
printf("%d\n", a.used);
freeArray(&a);