函数指针
通常我们可以将指针指向某类型的变量,称为类型指针(如,整型指针)。若将一个指针指向函数,则称为函数指针。
函数名的意义
函数名代表函数的入口地址,同样的,我们可以通过根据该地址进行函数调用,而非直接调用函数名。
1 void test001(){ 2 printf("hello, world"); 3 } 4 5 int main(){ 6 7 printf("函数入口地址:%d", test001);//qt中的函数入口地址不会变,C中会变,这里仅为了说明问题 8 //test001(); 9 int *testADD = (int *)20123883;//将地址转化为int型指针 10 void(*myfunc)() = testADD;//将函数写成函数指针,有些书上会写&testADD 11 myfunc(); //调用函数指针 12 system("pause"); 13 return 0; 14 }
另外,还有以下结论:
(1)test001的函数名与myfunc函数指针都是一样的,即都是函数指针。test001函数名是一个函数指针常量,而myfunc是一个函数指针变量,这是它们的关系。
1 int test001(int a, char b){ 2 printf("hello, world\n"); 3 return 0; 4 } 5 6 int main(){ 7 8 int(*myFun)(int, char) = test001; 9 myFun = test001; 10 11 //下面四种表达式的结果是相同的 12 int a = 10; 13 char b = 's'; 14 myFun(a, b); 15 (*myFun)(a, b); 16 test001(a, b); 17 (*test001)(a, b); 18 19 system("pause"); 20 return 0; 21 }
(2)testADD和&testADD的值一样,但表达的含义不同,与数组名和“&数组名”类似,详见指针和数组的关系。
定义函数指针
定义函数指针最简单的是直接定义函数指针变量,另外还有定义函数类型和定义函数指针类型。
1 int test001(int a, char b){ 2 printf("hello, world\n"); 3 return 0; 4 } 5 6 void test002(){ 7 8 //定义函数类型 9 typedef int(Fun)(int, char); 10 Fun *funFir = test001; 11 12 //定义函数指针类型 13 typedef int(*FunP)(int, char); 14 FunP funSec = test001; 15 16 //定义函数指针变量 17 int(*funThi)(int, char) = test001; 18 }
回调函数
回调函数和普通函数完成的功能是一样的,但回调函数更灵活,普通函数在函数体中调用,失去了变量的灵活性。