Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337605
  • 博文数量: 92
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 960
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-21 19:38
文章分类

全部博文(92)

文章存档

2010年(71)

2009年(21)

我的朋友

分类: 嵌入式

2009-09-02 19:53:28

Reference: "Embedded Linux, C-language programming practice"

1. The concept of function pointers:
   In the C language: the nature of the pointer is a memory address, function pointer is a pointer to a function of the code in the code segment address of the pointer.
   For the function, its address and function name represents the same meaning
   In the C language programming, data structures and algorithms are two basic elements, through a function pointer, the algorithm can be embedded into data structure.

 

2. The usage of function pointers

  *the basic usage
    int add (int a, int b)
    {....}
    int sub (int a, int b)
    {....}
    int main ()
    (
      int (* pf) (int, int);
      pf = add;
      result = pf (100,200);
      pf = sub;
      result = pf (100,200);
     )


   * Type conversion:
   int add (int a, int b)
    {....}
    int sub (int a, int b)
    {....}
    int main ()
    (
      void * pf;
      pf = add;
      result = (int (*) (int, int) pf) (100,200);
      pf = sub;
      result = (int (*) (int, int) pf) (100,200);
     )


    * Function pointer type definition
   typedef int (* fun_t) (int, int);
   fun_t pf;
   pf = add;
   result = pf (100,200);


    * Function pointer as a structure member
struct source
(
   int a;
   int b;
   fun_t operation; / / equivalent to int * fun_t (int, int);
);
int main (int argc, char * argv [])
(
   struct source data;
   int result;
   data.a = 200;
   data.b = 100;
   data.operation = add;
   result = data.operation (data.a, data.b);
)

   * Function pointer being as a parameters of the function
int calculate (int a, int b, fun_t operation)
(
   int result;
   result = operation (a, b);
   return result;
)
  int main (int argc, char * argv [])
(
   int a, b, result;
   a = 200;
   b = 100;
   result = calculate (a, b, add);
   )

   * Function pointer as the function return value
fun_t getoperation (char a)
(
   fun_t result;
   switch (a)
  (
   case "+";
       result = add;
       break;
   case "-";
       result = sub;
       break;
   )
    return result;
)
int main (int argc, char * argv [])
(
   int a, b, result;
   char oper;
   a = 200;
   b = 100;
   oper ="+";
   result = getoperation (oper) (a, b);
)


   * Array of function pointers
enum (
       oper_add = 0,
       oper_sub
)
static const fun_t oper_table [oper_num] =
(
   add,
   sub
)
int main (int argc, char * argv [])
(
   int a, b, result;
   a = 200;
   b = 100;
   result = oper_table [oper_add] (a, b);
)

阅读(988) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~