【问题标题】:Function pointers usage [duplicate]函数指针用法[重复]
【发布时间】:2011-03-03 13:50:02
【问题描述】:

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

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

#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));
}

输出:

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

【问题讨论】:

标签: c++ function-pointers


【解决方案1】:

我会简化你的问题,以展示我认为你想知道的内容。

给定

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) 做同样的事情。

【讨论】:

  • 认为你有一个小错字,*mycall ---> myfunc
  • 很好的答案和很好的引用。
【解决方案2】:

因为无论是否使用解引用运算符,函数指针都会自动解析。

【讨论】:

    【解决方案3】:

    你不必在函数名前使用 &

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

    但是两种方式都有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 2020-04-13
      • 1970-01-01
      • 2015-07-01
      • 2014-01-04
      • 1970-01-01
      • 2013-05-30
      相关资源
      最近更新 更多