Search code examples
carraysfunction-pointerspointer-to-array

Why can we use function pointers both as (*func_ptr)() and func_ptr() to invoke a function,but not so for array pointers?


Suppose we have a function pointer func_ptr of type void (*func_ptr)().Then we know that using this we can invoke the function using this pointer both as :

    (*func_ptr)();
    func_ptr();

But again, suppose we have a pointer to an integer array int (*arr_ptr)[5], then why can't we refer to the array as arr_ptr[], and consequently its elements as arr_ptr[0],arr_ptr[1] etc? Why can we only use (*arr_ptr)[0] and (*arr_ptr)[1]?


Solution

  • The type of arr_ptr[0] is int [5]; the type of (*arr_ptr)[0] is int. If you wanted to, you could use arr_ptr[0][0].

    #include <stdio.h>
    
    int main(void) {
      int (*arr_ptr)[5];
      int a[2][5] = {{1, 2, 3, 4, 5}, {11, 12, 13, 14, 15}};
      arr_ptr = a;
      printf("%d %d\n", (*arr_ptr)[2], arr_ptr[1][2]);
      return 0;
    }
    

    You can see the code "running" at ideone.

    That a function pointer can be used either way is just (nice) sintactic sugar.