关于c中函数指针的2个问题
我有两个问题
我看到了
int (*Ptr)(int,int); Ptr=someOtherFuncion;
它不应该是那样的吗?
Ptr=&someOtherFuncion;
2.我学习了函数指针,就像那样回调
someOtherFunction(functionPointer)
如果我将一个不是指针的常规函数放在什么区别?
函数的名称几乎立即衰减到指向函数的指针,因此someOtherFunction
会衰减到&someOtherFunction
明确提供的相同指针。 事实上,运算符地址( &
)的操作数是衰变不会发生的少数几个地方之一。
这有一个有趣的结果:即使您取消引用函数指针,它也会立即再次衰减。 所以以下都是等价的:
someOtherFunction(1, 2); (*someOtherFunction)(1, 2); (**someOtherFunction)(1, 2); (***someOtherFunction)(1, 2);
所以,如果你感觉不舒服地分配一个没有明确地址的函数指针,那么无论如何都要把&
放在那里,但你不必这样做。
解决问题的第二部分:函数总是通过函数指针调用,但由于上面提到的即时衰减,可以像调用函数指针一样调用普通函数。