8.5指向函数的指针
输入两个函数,让用户选择函数,决定输出结果
#include<stdio.h>
int max(int x, int y) {
int z;
if (x > y) z = x;
else z = y;
return z;
}
int min(int x, int y) {
int z;
if (x > y) z = y;
else z = x;
return z;
}
int main() {
int min(int x, int y);
int max(int x, int y);
int (*p)(int, int);
p = max;
int a, b,c,n;
printf(“请输入两个是整数”);
scanf_s(“%d%d”, &a, &b);
printf(“请选择1或2”);
scanf_s(“%d”, &n);
if (n == 1) p = max;
else if (n == 2) p = min;
c = (*p)(a, b);
printf(“a=%d,b=%d\n”, a, b);
if (n == 1)printf(“max=%d\n”, c);
else printf(“min=%d\n”, c);
return 0;
}
8.5.4用指向函数的指针作函数参数
把函数的入口地址作为参数传递给其他函数
#include<stdio.h>
int min(int x, int y) {
int z;
if (x > y) z = y;
else z = x;
printf("最小值为");
return z;
}
int max(int x, int y) {
int z;
if (x > y) z = x;
else z = y;
printf("最大值为");
return z;
}
int sum(int x, int y) {
int z;
z = x + y;
printf("两数之和为");
return z;
}
int fun(int x, int y, int(*p)(int, int)) {
int result;
result = (*p)(x, y);
printf("%d\n", result);
return result;
}
int main() {
int fun(int x, int y, int(*p)(int, int));
int sum(int x, int y);
int max(int x, int y);
int min(