函数指针是指向函数的指针变量。 因而“函数指针”本身首先应是指针变量,只不过该指针变量指向函数。这正如用指针变量可指向整型变量、字符型、数组一样,这里是指向函数。如前所述,C在编译时,每一个函数都有一个入口地址,该入口地址就是函数指针所指向的地址。有了指向函数的指针变量后,可用该指针变量调用函数,就如同用指针变量可引用其他类型变量一样,在这些概念上是大体一致的。函数指针有两个用途:调用函数和做函数的参数。
函数指针的定义
函数指针的声明方法为:
返回值类型 (*指针变量名)([形参列表]);
函数指针的赋值
指针变量名 = 函数名;
此处的函数名应该是与函数指针的定义中拥有相同的返回值类型, 形参列表的.
函数指针的使用
例: 按照不同的排序方式对结构体进行排序.
Function.h
struct student {
char name[20];
char sex;
int age;
float score;
int index;
};
typedef struct student Student;
typedef BOOL (*SORT)(Student s1, Student s2);//对函数指针起别名
void printStudent(Student stu[], int count);
void sortStudentArray(Student *stus, int count, SORT p);
BOOL cmpByNameAsc(Student s1, Student s2);//按照姓名升序排序
BOOL cmpByAgeAsc(Student s1, Student s2);//按照年龄升序排序
BOOL cmpByNameDes(Student s1, Student s2);//按照姓名降序排序
Function.m
void printStudent(Student stu[], int count) {
for (int i = 0; i < count; i++) {
printf("%-10s, %c, %d, %.2f, %d\n", stu[i].name, stu[i].sex, stu[i].age, stu[i].score, stu[i].index);
}
}
void sortStudentArray(Student *stus, int count, SORT p) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (p(stus[j], stus[j + 1])) {
Student t = stus[j];
stus[j] = stus[j + 1];
stus[j + 1] = t;
}
}
}
}
BOOL cmpByNameAsc(Student s1, Student s2) {
return strcmp(s1.name, s2.name) > 0 ? YES : NO;
}
BOOL cmpByAgeAsc(Student s1, Student s2) {
return s1.age > s2.age ? YES : NO;
}
BOOL cmpByNameDes(Student s1, Student s2) {
return strcmp(s1.name, s2.name) < 0 ? YES : NO;
}
main.m
//定义结构体数组,包含五个元素
Student stus[] = {
{"xiaoming", 'w', 19, 83, 119},
{"zhangsan", 'w', 20, 30, 120},
{"lisi", 'm', 28, 69, 110},
{"wangwu", 'w', 22, 99, 111},
{"wuxie", 'w', 34, 83, 108}
};
//元素个数
int count = sizeof(stus) / sizeof(Student);
/*
//输出结构体数组
printStudent(stus, count);
findStudentByScore(stus, count, addStr);
printf("验证:\n");
printStudent(stus, count);
*/
//动态排序:
//周一, 姓名降序
printf("周一, 姓名降序:\n");
sortStudentArray(stus, count, cmpByNameDes);
printStudent(stus, count);
//周二, 年龄升序
printf("周二, 年龄升序:\n");
sortStudentArray(stus, count, cmpByAgeAsc);
printStudent(stus, count);
//周三, 姓名升序
printf("周三, 姓名升序:\n");
sortStudentArray(stus, count, cmpByNameAsc);
printStudent(stus, count);