1.函数指针变量
// 函数指针的类型确定步骤:
1⃣ 把函数名换成(*函数指针变量名) 函数指针变量不能与函数名重名
1. void printfhello();↓
void (*函数指针变量名)() 无参数型
2. int sum (int a ,int b ) 有参数型
int (*函数指针变量名)(int ,int );
// 有参数 把参数名去掉 保留参数类型
2.返回值类型
1⃣(*函数指针变量名)(参数类型1,参数类型2…)= 初始值 ;
1.无参数时 两个括号也得有(*函数指针变量名)()
() 调用时叫函数调用符
void (*hello)() = NULL;
- 有参数的函数指针:
int (*Sum)(int ,int )=NULL;
hello=printfhello;
printfhello();
hello();
int(*SUM)(int ,int )= sum;// 可以赋空值 也可以赋已有的函数名
正常调用
int result = sum (3,5);
printf("%d\n",result);
- typedef 原始类型 新类型;
typedef int (*) (int ,int ) FUN ;error这个错
给函数指针类型起别名
typedef int (*新名字)(参数类型,参数类型);
typedef int (*FUN ) (int ,int );
例题:
1.// 用指针调用函数
void swp(int *a,int *b){
// 空的也可以
}
///运行时函数
int getValue (int a ,int b,int (*p)(int ,int)){
return p (a,b);
}
typedef struct student{
char name[15];
int age;
float score;
}Student;
2.//比较学生姓名
//BOOL (*)(Student,Student)
BOOL comparename(Student stu1,Student stu2);
BOOL comparename(Student stu1,Student stu2){
if (strcmp (stu1.name,stu2.name)>0) {
return YES;
}else{
return NO;
}//return strcmp(stu1.name ,stu2.name )>0;
}
//BOOL (*)(Student,Student)
BOOL compareage(Student stu1,Student stu2);
BOOL compareage(Student stu1,Student stu2){
return stu1.age>stu2.age;
/* if ( stu1.age>stu2.age) {
return YES;
}else{
return NO;
*/
}
//BOOL (*)(Student,Student)
BOOL comparescore(Student stu1,Student stu2);
BOOL comparenscore(Student stu1,Student stu2){
return stu1.score>stu2.score;
/* if ( stu1.score>stu2.score) {
return YES;
}else{
return NO;
*/
}
void printfArray(Student *stuArray,int count);
void bubbleSortArray(Student *stuArray,int count,BOOL (*p)(Student,Student)){
for (int i =0; i <count-1; i++) {
for (int j =0; j < count-i-1; j++) {
// 替换成函数指针,实现函数回调
if (p(stuArray[j],stuArray[j+1])) {
Student temp = {0};// 结构体
temp = stuArray[j];
stuArray[j]= stuArray[j+1];
stuArray[j+1]= temp;
}
}
}//遍历数组的函数
printfArray(stuArray, count);
}
void printfArray(Student *stuArray,int count){
for (int i =0; i <count; i++) {
printf("%s %d %.1f\n",stuArray[i].name,stuArray[i].age,stuArray[i].score);
}}