I worte a test program to understand callback functions and function pointers.The program is given below.
My question is while assigning
cb_display = (void*)display_struct; I have to cast the function to a void*. Why is this required even when the return type of function is void?
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int a; char b[16]; }myst_t; void (*cb_display)(void*); void display_struct(myst_t *st){ fprintf(stdout, "a -> %d b -> %s \n",st->a,st->b); } int main() { myst_t myst; myst.a = 789432; strncpy(myst.b,"helloabcd",9); cb_display = (void*)display_struct; cb_display(&myst); return 0; }
void *can only be converted to/from an object pointer, not a function pointer. If you do it right, thre is no need for a cast either. Get your types right!void*vs.myst_t*).