【问题标题】:Function Pointer in CC中的函数指针
【发布时间】:2010-11-19 17:08:17
【问题描述】:

如何在 C 中创建“函数指针”(并且(例如)函数具有参数)?

【问题讨论】:

标签: c pointers function-pointers


【解决方案1】:

http://www.newty.de/fpt/index.html

typedef int (*MathFunc)(int, int);

int Add (int a, int b) {
    printf ("Add %d %d\n", a, b);
    return a + b; }

int Subtract (int a, int b) {
    printf ("Subtract %d %d\n", a, b);
    return a - b; }

int Perform (int a, int b, MathFunc f) {
    return f (a, b); }

int main() {
    printf ("(10 + 2) - 6 = %d\n",
            Perform (Perform(10, 2, Add), 6, Subtract));
    return 0; }

【讨论】:

  • 有趣的例子 - 添加一个浮点数和两个字符?
  • 当然,你不是一直想将 3.145 添加到 'z' 并以整数形式返回结果吗!?我将把这个例子改得更理智一些。
【解决方案2】:
    typedef int (*funcptr)(int a, float b);

    funcptr x = some_func;

    int a = 3;
    float b = 4.3;
    x(a, b);

【讨论】:

    【解决方案3】:

    当我第一次深入研究函数指针时,我发现这个网站很有帮助。

    http://www.newty.de/fpt/index.html

    【讨论】:

      【解决方案4】:

      首先声明一个函数指针:

      typedef int (*Pfunct)(int x, int y);
      

      几乎与函数原型相同。
      但现在您创建的只是一种函数指针(使用typedef)。
      所以现在你创建了一个该类型的函数指针:

      Pfunct myFunction;
      Pfunct myFunction2;
      

      现在为它们分配函数地址,您可以像使用函数一样使用它们:

      int add(int a, int b){
          return a + b;
      }
      
      int subtract(int a, int b){
          return a - b;
      }
      
      . . .
      
      myFunction = add;
      myFunction2 = subtract;
      
      . . .
      
      int a = 4;
      int b = 6;
      
      printf("%d\n", myFunction(a, myFunction2(b, a)));
      

      函数指针很有趣。

      【讨论】:

        【解决方案5】:

        您还可以定义返回函数指针的函数:

        int (*f(int x))(double y);
        

        f 是一个函数,它接受单个 int 参数并返回一个指向函数的指针,该函数接受一个 double 参数并返回 int。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-23
          • 2021-10-30
          • 1970-01-01
          • 1970-01-01
          • 2018-07-28
          • 1970-01-01
          相关资源
          最近更新 更多