指向函数的指针
- 定义实现功能的不同的函数
- 找出最大值的函数 max,
- 找出最小值的函数 min,
- 相加的函数 add,
- 定义一个函数 process 来有效结合这三个函数,通过指向函数的指针来完成这个步骤
- 指向函数的指针用如下格式来定义
指针类型 (*指针变量名)()--->int(*p)()
这个指针的类型适合指针指向的函数的返回值类型保持一致的,例如max
函数的返回值类型是int
,因此指向max
函数的指针的类型也是int
- 在调用
process
函数的时候,想用哪个函数来处理数据,就把目标函数的地址付给函数指针p
即可;如下例所示。 - 之所以能够直接用指针指向函数,是因为 C 的代码运行的过程中,函数也会被载入内存从而开辟一块内存空间,函数开始的语句的地址就是函数的地址,因此,可以用指针直接指向函数。
#include<stdio.h> int max(int x, int y) { int result = (x > y) ? x : y; return result; } int min(int x, int y) { int result = (x > y) ? y : x; return result; } int add(int x, int y) { int result = x + y; return result; } int process(int x, int y, int(*p)()) { int result; if (p == max) { result = max(x, y); printf("最大值是:%d\n", result); } else if (p==min) { result = min(x, y); printf("最小值是:%d\n", result); } else { result = add(x, y); printf("两数之和:%d\n", result); } return result; } void main() { int a = 5, b = 6; int max_ = process(a, b, max); int min_ = process(a, b, min); int sum_ = process(a, b, add); }
返回指针值的函数
- 返回整形的函数的定义格式是
int func(参数列表)
,那么返回指针值的函数,就以如下形式来定义:int *func(参数列表)
用一个实例来进行展示:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int* search_student(int (*array)[4],int index) {
int(*p)[4] = array; //定义一个二维数组的指针类型
printf("正在搜索第%d个学生的成绩...\n\n", index);
return *(p + index);
}
void main() {
int array[][4] = { {93,92,98,95},{87,90,76,82},{90,86,98,87} };
int a;
printf("请输入您想要查询的学生的序号:\n\n");
scanf("%d", &a);
int *student_scores = search_student(array, a);
printf("第%d 个学生的成绩是:\n\n%d %d %d %d",a, student_scores[0], student_scores[1], student_scores[2], student_scores[3]);
}