代码之家  ›  专栏  ›  技术社区  ›  chaitanyavarma

函数指针用法[重复]

  •  3
  • chaitanyavarma  · 技术社区  · 16 年前

    可能重复:
    How does dereferencing of a function pointer happen?

    嗨,大家好, 为什么这两个代码的输出相同, 案例1:

    #include <stdio.h>
    
    typedef void (*mycall) (int a ,int b);
    void addme(int a,int b);
    void mulme(int a,int b);
    void subme(int a,int b);
    
    main()
    {
        mycall x[10];
        x[0] = &addme;
        x[1] = &subme;
        x[2] = &mulme;
        (x[0])(5,2);
        (x[1])(5,2);
        (x[2])(5,2);
    }
    
    void addme(int a, int b) {
        printf("the value is %d\n",(a+b));
    }
    void mulme(int a, int b) {
        printf("the value is %d\n",(a*b));
    }
    void subme(int a, int b) {
        printf("the value is %d\n",(a-b));
    }
    

    输出:

    the value is 7
    the value is 3
    the value is 10
    

    案例2:

    #include <stdio.h>
    
    typedef void (*mycall) (int a ,int b);
    void addme(int a,int b);
    void mulme(int a,int b);
    void subme(int a,int b);
    
    main()
    {
        mycall x[10];
        x[0] = &addme;
        x[1] = &subme;
        x[2] = &mulme;
        (*x[0])(5,2);
        (*x[1])(5,2);
        (*x[2])(5,2);
    }
    
    void addme(int a, int b) {
        printf("the value is %d\n",(a+b));
    }
    void mulme(int a, int b) {
        printf("the value is %d\n",(a*b));
    }
    void subme(int a, int b) {
        printf("the value is %d\n",(a-b));
    }
    

    输出:

    数值为7
    数值为3
    数值为10
    
    3 回复  |  直到 16 年前
        1
  •  5
  •   Tim Schaeffer    16 年前

    我会简化你的问题,让你知道我想知道的。

    鉴于

    typedef void (*mycall)(int a, int b);
    mycall f = somefunc;
    

    你想知道为什么

    (*f)(5, 2);
    

    和

    f(5.2);
    

    做同样的事情。答案是一个函数名都代表一个“函数指示符”。根据标准:

    "A function designator is an expression that has function type. Except when it is the
    operand of the sizeof operator or the unary & operator, a function designator with
    type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
    function returning type’’."
    

    使用间接运算符时 * 在函数指针上,该引用也是一个“函数指示符”。根据标准:

    "The unary * operator denotes indirection. If the operand points to a function, the result is
    a function designator;..."
    

    所以 f(5,2) 从本质上来说 (*f)(5,2) 按照第一条规则。这变成 call to function designated by f with parms (5,2) 其次。结果是 F(5,2) 和 (*f)(5,2) 做同样的事情。

        2
  •  3
  •   John Weldon user3678248    16 年前

    因为函数指针是自动解析的,不管您是否使用了取消引用操作符。

        3
  •  2
  •   noisy    16 年前

    您不必在函数名之前使用

    x[0] = addme;
    x[1] = subme;
    x[2] = mulme;
    

    然而,这两种方法都是有效的。

    推荐文章