簡體   English   中英

通過函數指針調用函數 - 是否取消引用指針? 有什么不同?

[英]Calling a function through a function pointer - dereference the pointer or not? What's the difference?

我嘗試了CC++ ,兩者都工作正常。

我對函數指針有點陌生,這里有一個簡單的代碼,讓我感到驚訝:

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

那么,兩者有什么區別

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確實是一個指針,那么顯式取消引用它會使讀者更清楚。 一般來說; 在一種情況下,您可以直接在指向函數的指針上調用函數這一事實很有用:在模板中,它使指向函數的指針成為功能對象,其行為與帶有operator()()的類完全相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM