zoukankan      html  css  js  c++  java
  • 33.函数指针相关问题

    • 函数指针作为参数
       1 #include <stdio.h>
       2 #include <stdlib.h>
       3 #include <Windows.h>
       4 
       5 int add(int a, int b)
       6 {
       7     return a + b;
       8 }
       9 
      10 int sub(int a, int b)
      11 {
      12     return a - b;
      13 }
      14 
      15 int mul(int a, int b)
      16 {
      17     return a*b;
      18 }
      19 
      20 int chu(int a, int b)
      21 {
      22     return a / b;
      23 }
      24 
      25 //函数指针作为参数
      26 int run(int(*p)(int,int), int a, int b)
      27 {
      28     return p(a, b);
      29 }
      30 
      31 void main()
      32 {
      33     int res = run(add, 10, 2);
      34     printf("%d
      ", res);
      35     system("pause");
      36 } 

        

    • 函数指针作为返回值
      1 //返回一个函数指针
      2 //返回的类型是(*p)(int,int)
      3 int (*p())(int,int)
      4 {
      5     return add;
      6 }

    一个复杂的例子,返回值是函数指针,参数是函数指针

     1 //返回一个函数指针
     2 //返回的类型是(*p)(int,int)
     3 int(*p(  int(*op)(int,int)  ))(int, int)
     4 {
     5     return op;
     6 }
     7 
     8 void main()
     9 {
    10     printf("%d
    ", p(sub)(1,2));
    11     system("pause");
    
    12 }
    •  typedef 简化函数指针
      1 typedef int(*pf)(int, int);
      2 pf p1 = add;
      3 printf("%d", p1(1, 2));
    •  函数指针数组
      1     int(**p)(int, int) = (int (*[])(int, int)){ add, sub, mul, chu };
      2     printf("%d
      ",(*(p+1))(1, 2));
      3     system("pause");
    • typedef简化函数指针数组
      1 typedef int(**pp)(int, int);
      2 typedef int(*px[10])(int, int);
      1 pp pp1 = (px){ add, sub };
      2 printf("%d
      ", pp1[0](2,4));
  • 相关阅读:
    ZOJ 3556
    ZOJ 2836
    HDU 2841
    HDU 4135
    POJ 3695
    POJ 2773
    HDU 4407
    HDU 1796
    ZOJ 3688
    ZOJ 3687
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8310496.html
Copyright © 2011-2022 走看看