So, I implement the functionality in the company I work for, and I have some doubts about callbacks and function pointers. Here is a sample code:
struct callback {
int (*func) (int *, int);
};
static struct callback cbstruct;
void install_func(struct callback *cbstruct, int (*func) (int *, int))
{
cbstruct->func = func;
}
int write(int *integ)
{
return *integ;
}
int main() {
int * a = malloc(sizeof(a));
*a = 5;
install_func(&cbstruct, write);
printf("%d\n", (cbstruct.func)(a,3));
return 0;
}
As you can see, this program registers a callback for a structure using a function pointer. The function is expected to receive two parameters (int * and int), but in the code example, the "write" function receives only int *.
I expect it to give me a compilation error, but there is only a warning:
funcpointer.c:24:26: warning: passing argument 2 of ‘install_func’ from incompatible pointer type
install_func(&cbstruct, write);
^
funcpointer.c:10:6: note: expected ‘int (*)(int *, int)’ but argument is of type ‘int (*)(int *)’
void install_func(struct callback *cbstruct, int (*func) (int *, int))
^
This program seems to work correctly by printing 5 on the screen, but I'm not sure if it is written correctly, given the difference in the number of parameters in the definition and declaration.
(-)? ? , (3), main.
, ( ), , , , () .
!