Search code examples
cfunctionfunction-pointers

can we have a double function pointer in C?


I am wondering that unlike the double pointers (int**) , can we have double function pointer?

I mean the function pointer pointing to the address of the another function pointer ?

I want something like

int add(int A , int B){
    return A+B;
}

int main(void){

    int (*funcpointerToAdd)(int,int) = add; // single function pointer pointing to the function add
    printf("%d \n",funcpointerToAdd(2,3));
  

    int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
    printf("%d \n",doubleFuncPointerToAdd(2,3));

    return 0;
}

but this gives me an error called object ‘doubleFuncPointerToAdd’ is not a function or function pointer

is this possible to do this thing anyway ?


Solution

  • You can use pointers to pointers to functions, but you have to deference them once first:

    int add(int A , int B){
        return A+B;
    }
    
    int main(void){
    
        int (*funcpointerToAdd)(int,int) = &add;
    //By the way, it is a POINTER to a function, so you need to add the ampersand
    //to get its location in memory. In c++ it is implied for functions, but
    //you should still use it.
        printf("%d \n",funcpointerToAdd(2,3));
      
    
        int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
        printf("%d \n",(*doubleFuncPointerToAdd)(2,3));
    //You need to dereference the double pointer,
    //to turn it into a normal pointer, which you can then call
    
        return 0;
    }
    

    This is also true for other types:

    struct whatever {
       int a;
    };
    
    int main() {
       whatever s;
       s.a = 15;
       printf("%d\n",s.a);
       whatever* p1 = &s;
       printf("%d\n",p1->a); //OK
    //x->y is just a shortcut for (*x).y
       whatever** p2 = &p1;
       printf("%d\n",p2->a); //ERROR, trying to get value (*p2).a,
    //which is a double pointer, so it's equivalent to p1.a
       printf("%d\n",(*p2)->a); //OK
    }