一,函数指针定义
函数名和数组名一样都是地址,函数名存储在代码区,由于是个常量,不能进行修改,要赋值给一个函数指针变量。
函数指针定义例如:int maxValue(int a,int b) int (*p)(int a,int b) =NULL; p 是变量,除了之外的是类型。
使用: p = maxValue;指针可以当函数用
typedef int(*p)(int a,int b) 为int (*)(int ,int)这个类型重新定义为p;
// int maxValue(int a, int b);
// int p(int a, int b);函数
// int *p(int a,int b)) function 返回值为 int *的函数
// int (*p)(int a, int b) //p就是一个函数指针变量
// int (*p)(int, int); 表示定义一个返回值为int 并且有两个int型的参数的函数指针,任何与其格式一致的函数都可以将首地址保持在指针变量p中。
// int (*p)(int, int);
// p = sumValue;
// int sum = p(8, 9);
// printf("p --> %p\t\tsumValue --> %p\n", p,sumValue);
// //当函数指针变量P保存了函数sumValue的首地址后,就可以与函数名sumValue有等效代换的作用,函数调用时用函数名与用函数指针变量,效果一样。
// int result1 = sumValue(3, 5);
// int result2 = p(3, 5);
// printf("result1 = %d\n",result1);
// printf("result2 = %d\n",result2);
int value = getValue(3,5,maxValue);
getValue 执行的过程中再调用(回调)MaxValue;
三 动态排序。四 函数返回值是函数指针
排序需求不定,按照姓名?成绩?年龄?
把决定排序方式的重要语句封装成函数,然后调用。
typedef BOOL (*compare)(int, int);
void bubbleSort(int *array, int count,compare cmp);
void bubbleSort(int *array, int count, compare cmp){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (cmp(array[j], array[j + 1])) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
typedef struct functionList{
char *funcName; //函数名称字符串
compare function; //函数指针变量
}functionList;
BOOL ascending(int a,int b);
BOOL ascending(int a,int b){
return a > b ? YES : NO;
}
BOOL descending(int a,int b);
BOOL descending(int a,int b){
return a < b ? YES : NO;
}
void printArray(int *array, int count);
void printArray(int *array, int count){
for (int i = 0; i < count; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
functionList list[2] = {{"asc", ascending}, {"desc", descending}};
compare getFuntionByName(char *name);
compare getFuntionByName(char *name){
for (int i = 0; i < 2; i++) {
int result = strcmp(list[i].funcName, name);
if (result) {
return list[i].function;
}
}
return NULL;
}