I'm trying to write a generic function to print the elements of an array. This is what I have:
void printArray(void * source, int numElements, int size, void (*printFunction)(void *)){
void *dest[numElements];
memcpy(dest, &source, (size * nElem));
int i;
for (i = 0; i < numElements; i++){
printFunction(dest[i]);
}
}
I am passing in the address of an array, the number of elements in the array, the size of each element in the array, and a callback function to handle printing/formatting for whichever type of array it is (the printing function works fine, I've tested it).
Right now it's printing out the first element, then I'm getting a segmentation fault. I'm having trouble figuring out what the problem is - any help would be greatly appreciated. I'm new to stackoverflow so let me know if I can improve my question.
Why are you copying at all?
What you actually want is to pass a char pointer, that way you can increment it by
size
from0
tonumElements
times, passing it to printFunction each time.Notice, you've actually written a more general function than something that just prints an array. You're effectively writing a 'map' function that maps a function on to an array.
Something like this should work (note it's untested):