函数指针的使用
问题描述:
可能重复:
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));
}
输出:
the value is 7
the value is 3
the value is 10
答
我会简化您的问题,以显示我认为您想知道的内容。
鉴于
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)
做同样的事情。
答
因为无论你用或不用引用操作使用这些函数指针自动解决。
答
你没有之前函数名
x[0] = addme;
x[1] = subme;
x[2] = mulme;
但是这两种方式都是有效的使用&。
有人编辑并放入代码形式请 – geshafer 2010-06-14 15:17:58
重复[如何解除函数指针的引用?](http://stackoverflow.com/questions/2795575/how-does-dereferencing-of-a-function-指针 - 发生) – 2010-06-14 15:21:34