I've got a group of functions that can create, insert into, and free() a dynamic array, but I've run into a problem where I need two different data types for separate arrays.
Would it be possible, in initArray() and insertArray() to pass an argument that literally holds a data type (char, int, etc..) that way I don't have to define multiple functions?
// struct for dynamic array
typedef struct ArrayStruct {
char *array;
size_t used;
size_t size;
} Array;
// create the array
void initArray(Array *a, size_t initialSize)
{
a->array = malloc(initialSize * sizeof(char));
a->used = 0; // number of entries
a->size = initialSize;
}
// insert elements into the array
void insertArray(Array *a, char element)
{
// a->array[a->used++] updates a->used after the array has been accessed
// so a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(char));
}
a->array[a->used++] = element;
}
// free memory allocated to the array after done
void freeArray(Array *a)
{
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}