深入了解函数指针与指针函数

来源:互联网 发布:淘宝开店成功率 编辑:程序博客网 时间:2024/06/05 16:02

  一,概念

函数指针:指向函数的指针变量,本质上是一个指针变量,指向的是一个函数

指针函数:顾名思义就是带有指针的函数,即其本质是一个函数,只不过这种函数返回的是一个对应类型的地址,即返回的是一个指针。

二,定义

 函数指针: type (*func)(type , type ),如 void (*func)(void),定义一个指向void类型的指针变量。

 指针函数: type  *func (type , type),如 int *func(void),定义一个返回int型的指针函数。

三,代码演示

1,指针函数

  1. #include <stdio.h>  
  2.   
  3. int*fun(int *a)  
  4. {  
  5.     return a;  
  6. }  
  7. int main(int argc, char **argv)  
  8. {  
  9.     int a = 3;  
  10.     printf("%d", *(fun(&a)));  
  11.     return 0;  


2,函数指针

①最简单的一种函数指针形式:

  1. #include <stdio.h>  
  2. typedef int (*Func)(int);   //声明指针  
  3. Func func;
  4. int fun(int i)  
  5. {  
  6.     return i + 1;  
  7. }  
  8. int main(int argc, char **argv)  
  9. {  
  10.     int r;  
  11.     func = fun;     //给指针赋值  
  12.     r = (*func)(5);     //调用  
  13.     printf("%d\n", r);  
  14.     return 0;  
  15. }  

typedef的功能是定义新的类型,第2句就是定义了一种Func的类型,并定义这种类型为指向某种函数的指针,这种函数以一个int为参数并返回int类型。后面就可以像使用int,char一样使用Func了。

②函数指针数组的应用:


  1. #include "stdio.h"

  2. double app_add(double a,double b) 
  3. {
  4.    return a+b;
  5. }
  6. double app_sub(double a,double b)
  7. {
  8.   return a-b;
  9. }
  10. /*函数指针数组申明*/
  11. double (*app_func[])(double, double) = {  
  12.     app_add,app_sub
  13. };  

  14. int main(int argc, const char * argv[])  
  15. {  
  16.   
  17.     int oper = 0;  
  18.     int op1 = 5;  
  19.     int op2 = 8;  
  20.     int result = app_func[oper](op1,op2);  //oper=0调用app_add函数;oper=1调用app_sub函数。
  21.     printf("%d",result);  
  22.     return 0;  
  23. }  
  24.   


③函数指针结构体与数组的应用:

typedef void (*App_Func)(void);


typedef struct {
App_Func  app_func1;  
App_Func  app_func2;
} tApp_t;


enum {
MODE_IDLE = 0,
MODE_INIT,
MODE_MAX
};
const tApp_t Tab[MODE_MAX]=

{

/*IDLE*/

{

app_idle_fun1,

app_idle_fun2

},

/*INIT*/

{

app_init_fun1,

app_init_fun2

},

};

void app_idle_fun1()

{

}

void app_idle_fun2()

{

}

void app_init_fun1()

{

}

void app_init_fun2()

{

}

int main (void)

{

    Tab[MODE_IDLE ].app_idle_fun1(); //调用app_idle_fun1函数

return 0;

}