因此,这种简单的情况只是在传递函数时输出3
:
#include <stdio.h>
int
add(int a, int b) {
return a + b;
}
int
case_1_fn_a(int fn_x(int, int)) {
return fn_x(1, 2);
}
int
main() {
int x = case_1_fn_a(add);
printf("%d\n", x);
return 0;
}
但是现在我想将函数传递给函数。我该怎么办?
#include <stdio.h>
int
add(int a, int b) {
return a + b;
}
int
case_2_fn_a(int fn_x(int, int), int fn_y(int, int)) {
return add(fn_x(add, add), fn_y(add, add));
}
int
case_2_fn_b(int fn_x(int, int)) {
return fn_x(1, 2);
}
int
main() {
int x = case_2_fn_a(case_2_fn_b, case_2_fn_b);
printf("%d\n", x);
return 0;
}
但是我遇到了这些错误(如果尝试调整此错误,那我会遇到各种不同的错误,所以没有任何效果):]
,并带有一些函数作为参数。然后,函数“ B”,“ C”和“ D”将使用其函数参数,并将简单的值(例如整数或字符)传递给它们。tmp.c:11:19: warning: incompatible pointer to integer conversion passing 'int (int, int)' to parameter of type 'int' [-Wint-conversion] return add(fn_x(add, add), fn_y(add, add)); ^~~ tmp.c:11:24: warning: incompatible pointer to integer conversion passing 'int (int, int)' to parameter of type 'int' [-Wint-conversion] return add(fn_x(add, add), fn_y(add, add)); ^~~ tmp.c:11:35: warning: incompatible pointer to integer conversion passing 'int (int, int)' to parameter of type 'int' [-Wint-conversion] return add(fn_x(add, add), fn_y(add, add)); ^~~ tmp.c:11:40: warning: incompatible pointer to integer conversion passing 'int (int, int)' to parameter of type 'int' [-Wint-conversion] return add(fn_x(add, add), fn_y(add, add)); ^~~ tmp.c:21:23: warning: incompatible pointer types passing 'int (int (*)(int, int))' to parameter of type 'int (*)(int, int)' [-Wincompatible-pointer-types] int x = case_2_fn_a(case_2_fn_b, case_2_fn_b); ^~~~~~~~~~~ tmp.c:10:17: note: passing argument to parameter 'fn_x' here case_2_fn_a(int fn_x(int, int), int fn_y(int, int)) { ^ tmp.c:21:36: warning: incompatible pointer types passing 'int (int (*)(int, int))' to parameter of type 'int (*)(int, int)' [-Wincompatible-pointer-types] int x = case_2_fn_a(case_2_fn_b, case_2_fn_b); ^~~~~~~~~~~ tmp.c:10:37: note: passing argument to parameter 'fn_y' here case_2_fn_a(int fn_x(int, int), int fn_y(int, int)) { ^ 6 warnings generated. Segmentation fault: 11
本质上,我想将一系列函数传递给函数“ A”,然后让函数“ A”接受这些函数(我们称它们为函数“ B”,“ C”和“ D”),然后调用它们
所以这个简单的例子在传递函数时只打印出3:#include
如注释中所述,使用函数指针: