Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 401
Kiril Kirov Avatar asked Nov 20 '12 11:11

Kiril Kirov


1 Answers

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.

like image 104
P.P Avatar answered Oct 14 '22 21:10

P.P