C语言 函数指针 函数指针数组的用法

前述:C语言的奥秘,博大精深,今天来回忆的分析函数指针,函数指针数组的用法。具体请见下面一个注册程序的实现。    

  1 #include <stdio.h>
  2 #include <string.h>
  3   
  5 
  6 typedef void (*poniter_fun)(int);   //定义一个函数指针
  7 
  8 typedef struct poniter_desc {
  9         char *name;
 10         poniter_fun fp;
 11 } poniter_desc,*p_poniter_desc;
 12 
 13 poniter_desc poniter_array[10];    
 14 p_poniter_desc  p_poniter_array;
 15 
 16 int register_fun(char *name,poniter_fun fp)   //注册函数
 17 {
 18         int i;
 19         for(i=0;i<10;i++)
 20         {
 21                 if(!poniter_array[i].fp)
 22                         {
 23                                 poniter_array[i].name=name; poniter_array[i].fp=fp;
 25                                 return 0;
 26                         }
 27         }
 28         return -1;
 29 }
 30 int unregister_fun(char *name,poniter_fun fp)    //注销函数
 31 {
 32         int i;
 33         for(i=0;i<10;i++)
 34         {
 35                 if(!strcmp(poniter_array[i].name,name))
 36                         {
 37                                 poniter_array[i].name=NULL;
 38                                 poniter_array[i].fp=NULL;
 39                                 return 0;
 40                         }
 41         } return -1;
 43 }
 44 void run(void)     //调用
 45 {
 46         poniter_array[0].fp(1);
 47         poniter_array[1].fp(2);
 48 }
 49 
 50 void first(int i)
 51 {
 52         printf("this is first fun%d \r\n",i);
 53 }
 54 
 55 void second(int i)
 56 {
 57         printf("this is second fun%d \r\n",i);
 58 }
 59 
 60 
 61 
 62 void main()
 63 {

 65   register_fun("first",first);   //将函数加入注册函数
 66   register_fun("second",second);
 67   run();
 68 }



下面为函数相应的输出结果

[email protected]:~/myFile/fun_ponit$ ls
register  register.c
[email protected]:~/myFile/fun_ponit$ ./register 
this is first fun 1 
this is second fun 2 

猜你喜欢

转载自blog.csdn.net/dmc111qwf/article/details/80200868
今日推荐