C is naturally clumsy at polymorphism but I wanted to avoid duplication so I wrote this function. But I'm sure there are ways left to improve it. Please not that for brevity's sake not all data types have been included.
void print_int(const void *number) {
int result = *((int*) number);
printf("%d ", result);
}
void print_double(const void *number) {
double result = *((double*)number);
printf("%f ", result);
}
/// Prints arrays of arbitrary type
/// \param array The array to print
/// \param length The length of the array
/// \param type The data type xxx of the array elements in the form of "TYPE_XXX"
/// \return 1 in case of an invalid data type
int print_array(const void *array, size_t length, char *type) {
void (*function)(const void *number);
void *cast_array;
size_t size;
if (!strcmp(type, TYPE_INT)) {
function = print_int;
cast_array = (int *) array;
size = sizeof(int);
} else if (!strcmp(type, TYPE_DOUBLE)) {
function = print_double;
cast_array = (double *) array;
size = sizeof(double);
} else {
return 1;
}
for (size_t i = 0; i < length; ++i) {
function(cast_array + i * size);
}
printf("\n");
return 0;
}