I intend to understand the working of function pointers
in C.I wrote this program for a function which has a function pointer disp_function
that is expected to printed the contents of an array of any type,using the pointer ptr
to an intended destination,but it won't work:
void show_array(void* ptr, void (*disp_function)(void*), int nr_elem) {
int i=0;
while(i<nr_elem) {
(*disp_function) (ptr);
ptr++;
i++;
}
}
Here is an instance of the use of the program:
void show_movements(Movement* movs, int nr) {
void (*display_function) (void* ptr) = show_movement;
show_array(movs, display_function, nr);
}
void show_movement(void* ptr) {
Movement* ptr2 = NULL;
ptr2 = (Movement*) ptr;
printf("%d -> '%s'\n", ptr2->id, ptr2->title);
}
The program crashes in the last function.Here are the specifics of it:
- the array has several elements (> 2)
- the first one is printed correctly
- the program crashes when attempting to print the second element (verified by debugging)
I suppose it's the ptr++
which is causing the crash as I am incrementing a void*
.Also I tried using array syntax (*display_function) (ptr[i]);
but I always get an error invalid use of void expression
Can anyone give me an idea what's the exact cause of the problem?