Function Pointer

Posted jasperzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Function Pointer相关的知识,希望对你有一定的参考价值。

helloworld.c


#include<stdio.h> #include<stdlib.h> void Hello(); void Hello() { printf("Hello World! "); } int main() { void (*Hello_ptr)() = Hello; //giving the address of "Hello" funciton to the pointer (*Hello_ptr)(); //ugly way Hello_ptr(); //elegent way to use function pointer }

 

 Example2.c

int my_func(int a,int b);
int your_func(int , int);
int main()
{
  int (*funcPtr)(int,int); //declare a function pointer --> not pointing to anything now
  funcPtr = my_func; //initializing function pointer

  //use the function pointer
  int x = (*funcPtr)(5,7);
  //or
  int y = funcPtr(5,7);
}

math_pointers.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int sum(int a, int b);
 5 int subtract(int a, int b);
 6 int mul(int a, int b);
 7 int divide(int a, int b);
 8 
 9 int (*p[4]) (int x, int y);
10 
11 int main(void)
12 {
13   char buf[80];
14   int result;
15   int i, j, op;
16 
17   p[0] = sum; /* address of sum() */
18   p[1] = subtract; /* address of subtract() */
19   p[2] = mul; /* address of mul() */
20   p[3] = divide; /* address of divide() */
21 
22   printf("Enter two numbers: ");
23   fgets(buf, 80, stdin);
24   sscanf(buf, "%d %d", &i, &j);
25   
26   printf("0: Add, 1: Subtract, 2: Multiply, 3: Div, 4: Quit
");
27   printf("Enter number of operation: ");
28   fgets(buf, 80, stdin);
29   sscanf(buf, "%d", &op);
30 
31   while (op >= 0 && op <= 3)  {
32     result = (*p[op]) (i, j);
33     printf("%d

", result);
34 
35     printf("0: Add, 1: Subtract, 2: Multiply, 3: Div, 4: Quit
");
36     printf("Enter number of operation: ");
37     fgets(buf, 80, stdin);
38     scanf(buf, "%d", &op);
39   }
40 
41 
42   return 0;
43 }
44 
45 int sum(int a, int b)
46 {
47   return a + b;
48 }
49 
50 int subtract(int a, int b)
51 {
52   return a - b;
53 }
54 
55 int mul(int a, int b)
56 {
57   return a * b;
58 }
59 
60 int divide(int a, int b)
61 {
62   if (b)
63   {
64     return a / b;
65   }
66   else
67   {
68     return 0;
69   }
70 }

 

以上是关于Function Pointer的主要内容,如果未能解决你的问题,请参考以下文章

Function Pointer

function pointer x + y

26个jQuery代码片段使用技巧

discuz X3.1 源代码阅读,记录代码片段

vue2.0 代码功能片段

js常用代码片段