Fucntion pointers hold function addresses, not whole unmade function calls.
With
int func(int a, int b) { if (a == b) return 1; else return 0; }
int (*ptr)(int, int) = &func;
You can use
(*ptr)(1,2) //call a function through a function pointer
instead of
func(1,2) //call a function directly
.
(Technically, standardized C also allows ptr(1,2)
, or (*func)(1,2)
, or abominations such as (***&***&*ptr)(1,2)
, because regular function calls are defined in terms of decay to function pointers.)
To store an unmade function call, you need both the function address and the parameters:
struct callToIntIntInt{ int (*fn)(int, int); int arg1, arg2; };
struct callToIntIntInt calls[10];
calls[0] = (struct callToIntIntInt){ &func, 1, 1 };
calls[1] = (struct callToIntIntInt){ &func, 1, 0 };
/*...*/
calls[9] = (struct callToIntIntInt){ &func, 1, 0 };
/*...*/
int result = 0;
for (int i = 0; i < 10; i++)
result += calls[i].fn(calls[i].arg1, calls[i].arg2);
printf ("%d\n", result);
If the function pointers are all the same then of course storing them is a waste of space:
struct argsToIntIntInt{ int arg1, arg2; };
/*...*/
result += func(args[i].arg1, args[i].arg2);
With the syntax you proposed:
ptr[0] = func(1, 1);
ptr[1] = func(1, 0);
...
ptr[9] = func(0, 0);
you'd be making the function calls right then and there, the result would be int
(the return type of func
), and in that case, ptr
could just be int ptr[10];
(array of ten int
s–no function pointers).