码迷,mamicode.com
首页 > 其他好文 > 详细

Function Pointer

时间:2020-05-01 01:11:50      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:href   declare   The   fgets   --   span   http   scanf   style   

helloworld.c


#include<stdio.h> #include<stdlib.h> void Hello(); void Hello() { printf("Hello World!\n"); } 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\n");
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\n\n", result);
34 
35     printf("0: Add, 1: Subtract, 2: Multiply, 3: Div, 4: Quit\n");
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

标签:href   declare   The   fgets   --   span   http   scanf   style   

原文地址:https://www.cnblogs.com/JasperZhao/p/12812163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!