一、typedef定义函数指针类型
1.源码
2.c
#include <stdio.h>
typedef int (*HAL_CALL_BACK)(int,int);
int test(int a,int b);
int add(void* func,int a,int b);
int main(){
// printf("TK------>>>test is 0x%lx\n",test);
int result = add((void*) test,3,4);
printf("TK------>>>>result is %d\n",result);
return 0;
}
int test(int a,int b){
return a + b;
}
int add(void* func,int a,int b){
HAL_CALL_BACK test2 = (HAL_CALL_BACK)func;
int (*test1)(int,int) = (HAL_CALL_BACK)func;
//printf("TK------->>>>>func is 0x%lx\n",func);
return test1(a,b);
}
2.编译运行
gcc -o 2 2.c
./2
TK------>>>>result is 7
二、函数指针类型
1.理解int (* func)(int ,int )
在上面的表达式中从左到右有四个运算符()、*、();
运算符的优先级()比*高,()的结合方向是自左到右,*的结合方向是自右到左;
()结合是从左到右,这是定义了一个指针变量func,接下来是后括号,表明是定义一个函数类型的指针func;
接下来说明该变量func是一个指向,参数是两个int、返回值是一个int的函数,的指针变量。
2.源码
1.c
#include <stdio.h>
//typedef int (*HAL_CALL_BACK)(int,int);
int test(int a,int b);
int add(int func(int,int),int a,int b);
int main(){
// printf("TK------>>>test is 0x%lx\n",test);
int result = add(test,3,4);
printf("TK------>>>>result is %d\n",result);
return 0;
}
int test(int a,int b){
return a + b;
}
int add(int func(int,int),int a,int b){
int (*test1)(int,int) = func;
//printf("TK------->>>>>func is 0x%lx\n",func);
return test1(a,b);
}
2.编译和运行
gcc -o 1 1.c
./1
TK------>>>>result is 7