Per your title, you want a function that accepts an array whose element type is unknown to the function. There is no such function, because no array is ever passed as a function argument in C. Instead, if an expression designating a function argument evaluates to an array, that array further "decays" to a pointer to the first element of the array, and it is the pointer that is passed. Indeed, arrays decay to pointers in nearly all contexts.
Do not be fooled: C allows you to specify function parameter types via syntax that designates arrays in other places, but that is a convenience feature. The actual parameter types designated that way are the corresponding pointer types. That allows you to write matching variable and function parameter declarations if you wish to do so.
Now, since it's not your array of unknown (to the function) type that is passed, but rather a pointer to the first element of such an array, your question boils down to "how do I designate a pointer type that can hold a pointer to any type?" That one I bet you already know: void *
is the conventional way, but char *
also works:
void f(void *a) {
// ...
}
There's not much you can do with that alone, however. Compare with the interface to the standard library function qsort()
, which indeed accepts just such a pointer. For it to be able to use the pointer, it also takes arguments designating the size of each array element and the number of elements, and for its particular purposes it also accepts a pointer to a function suitable for comparing those elements.
Update:
Following the qsort()
model, if you want a function that prints the elements of any array, you might do this:
void print_elements(void *first, size_t element_size, size_t element_count,
void (*print_element)(void *)) {
char *element = first; // pointer arithmetic is not allowed on void *
for (size_t index = 0; index < element_count; index++) {
print_element(element);
element += element_size;
}
}
You could then use it like this:
void print_int(void *intp) {
printf("--%d--", *((int *) intp));
}
void main(void){
int a[5] = { 1, 2, 3, 4, 5 };
print_elements(a,
sizeof(a[0]), // The size of each element
sizeof(a) / sizeof(a[0]), // The number of elements
print_int); // A pointer to a suitable print function
}