通过函数指针调用函数 – 是否取消引用指针? 有什么不同?

我试过–C和C++都很好。

我是函数指针的新手,这是一个简单的代码,让我感到惊讶:

 #include  void sort( int* arr, const int N ); int main () { int arr1[] = { 1, 5, 2, 6, 2 }; int arr2[] = { 1, 5, 2, 6, 2 }; void (*sort_ptr)( int*, const int) = sort; sort_ptr( arr1, 5 ); (*sort_ptr)( arr2, 5 ); assert( arr1[0] == 1 && arr1[1] == 2 && arr1[2] == 2 && arr1[3] == 5 && arr1[4] == 6 ); assert( arr2[0] == 1 && arr2[1] == 2 && arr2[2] == 2 && arr2[3] == 5 && arr2[4] == 6 ); return 0; } void sort( int* arr, const int N ) { // sorting the array, it's not relevant to the question } 

那么,有什么区别

 sort_ptr( arr1, 5 ); 

 (*sort_ptr)( arr2, 5 ); 

两者似乎都工作(没有错误,没有警告,排序数组),我有点困惑。 哪一个是正确的或两者都是正确的?

 sort_ptr( arr1, 5 ); 

 (*sort_ptr)( arr2, 5 ); 

两者都是正确的。 事实上,你可以放置你想要的多个星号,它们都是正确的:

 (*****sort_ptr)( arr2, 5 ); 

函数名称衰减为指向函数的指针。 所以反复取消引用会产生相同的指针。

就编译器而言, sort_ptr(*sort_ptr)是相同的。 但是,如果sort_ptr确实是一个指针,那么显式解除引用会使读者更加清楚。 一般来说; 有一种情况,你可以直接在函数指针上调用一个函数是有用的:在模板中,它创建一个函数一个function对象的指针,其行为与一个带有operator()()的类完全相同。