c - Function pointers - pass arguments to a function pointer -
i have problem code uses function pointers, take look:
#include <stdio.h> #include <stdlib.h> typedef void (*vfuncv)(void); void fun1(int a, double b) { printf("%d %f fun1\n", a, b); } void fun2(int a, double b) { printf("%d %f fun2\n", a, b); } void call(int which, vfuncv* fun, int a, double b) { fun[which](a, b); } int main() { vfuncv fun[2] = {fun1, fun2}; call(0, fun, 3, 4.5); return 0; }
and produces errors:
/home/ivy/desktop/ctests//funargs.c||in function ‘call’:| /home/ivy/desktop/ctests//funargs.c|11|error: many arguments function ‘*(fun + (unsigned int)((unsigned int)which * 4u))’| /home/ivy/desktop/ctests//funargs.c||in function ‘main’:| /home/ivy/desktop/ctests//funargs.c|16|warning: initialization incompatible pointer type [enabled default]| /home/ivy/desktop/ctests//funargs.c|16|warning: (near initialization ‘fun[0]’) [enabled default]| /home/ivy/desktop/ctests//funargs.c|16|warning: initialization incompatible pointer type [enabled default]| /home/ivy/desktop/ctests//funargs.c|16|warning: (near initialization ‘fun[1]’) [enabled default]| ||=== build finished: 1 errors, 4 warnings ===|
i used code::blocks compile it.
its simple, when dont have arguments some, got confused:
#include <stdio.h> #include <stdlib.h> typedef void (*vfuncv)(void); void fun1() { printf("fun1\n"); } void fun2() { printf("fun2\n"); } void call(int which, vfuncv* fun) { fun[which](); } int main() { vfuncv fun[2] = {fun1, fun2}; call(1, fun); return 0; }
your function pointer not fit function declarations. try defining as
typedef void (*vfuncv)(int, double);
Comments
Post a Comment