我正在尝试创建一个函数:
int func(int a, int b) { if (a == b) return 1; else return 0; }
然后,我想创建一个函数指针,如:
int (*ptr)(int, int);
我如何动态分配ptr以使其能够容纳例如10个不同的函数调用?
ptr[0] = func(1, 1);
ptr[1] = func(1, 0);
...
ptr[9] = func(0, 0);
以便我可以通过类似这样的指针在FOR循环中调用函数:
int result = 0;
for (int i = 0; i < 10; i++)
result += ptr[i];
printf ("%d\n", result);
功能指针保存函数地址,而不是整个未进行的函数调用。
使用
int func(int a, int b) { if (a == b) return 1; else return 0; }
int (*ptr)(int, int) = &func;
您可以使用
(*ptr)(1,2) //call a function through a function pointer
代替
func(1,2) //call a function directly
。
ptr(1,2)或(*func)(1,2)
或类似(***&***&*ptr)(1,2)
的可憎性,因为常规函数调用是根据对函数指针的衰减定义的。)要存储未完成的函数调用,您需要函数地址和参数:
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);
如果函数指针全部相同,那么存储它们当然是浪费空间:
struct argsToIntIntInt{ int arg1, arg2; }; /*...*/ result += func(args[i].arg1, args[i].arg2);
使用您建议的语法:
ptr[0] = func(1, 1); ptr[1] = func(1, 0); ... ptr[9] = func(0, 0);
您将立即进行函数调用,结果将是int
(func
的返回类型),在这种情况下,ptr
可能只是int ptr[10];
(十个数组)int
s –无功能指针)。>