通过函数指针调用函数 - 解引用指针或不是?有什么不同? [英] Calling a function through a function pointer - dereference the pointer or not? What's the difference?

查看:635
本文介绍了通过函数指针调用函数 - 解引用指针或不是?有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过两个 - C C ++ ,两个都很好。



我有一个新的函数指针,这里有一个简单的代码,让我很惊讶:

  #include < assert.h> 
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)
{
//排序数组,它与问题不相关
}

因此,

之间有什么区别

  sort_ptr(arr1,5); 

 (* sort_ptr)(arr2,5); 

这两种方法似乎都有效(没有错误,没有警告,排序数组),我很困惑。

$

  sort_ptr(arr1,

5);

 (* sort_ptr)(arr2,5); 

两者都正确。事实上,你可以输入尽可能多的星号,他们都是正确的:

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

函数的名称衰减到指向函数的指针。所以反复解除引用会产生相同的指针。


I tried both - C and C++ and both work fine.

I'm kinda new to function pointers and here's a simple code, that surprised me:

#include <assert.h>
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
}

So, what's the difference between

sort_ptr( arr1, 5 );

and

(*sort_ptr)( arr2, 5 );

Both seems to work (no errors, no warnings, sorted arrays) and I'm kinda confused. Which one is the correct one or they both are correct?

解决方案

sort_ptr( arr1, 5 );

and

(*sort_ptr)( arr2, 5 );

Both are correct. In fact, you can put as many asterisks you want and they are all correct:

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

The name of function decays to a pointer to a function. So dereferencing it repeatedly is going to produce the same pointer.

这篇关于通过函数指针调用函数 - 解引用指针或不是?有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆