Suppose we have the following functions (in C):
int sum(int a, int b){ return a+b; } int diff(int a, int b){ return ab; }
So we know that we can declare an array of funtion pointers as follows:
int (*test[2]) (int a, int b); test[0] = sum; test[1] = diff;
But the following is also true (but we use heap allocation):
int (**test) (int a, int b) = malloc( 2*sizeof(*test)); test[0] = sum; test[1] = diff;
So far so good. Now recall that to declare an (dynamically allocated) array of two integers, we can do:
int* test = malloc( 2*sizeof(int));
So why can't we declare an array of function pointers as
int (*test) (int a, int b) = malloc( 2*sizeof(*test)); ?
Is it the reason that the test is the same as *test and **test (etc.), malloc( 2*sizeof(*test)) returns a pointer to a function pointer and therefore cannot be assigned (*test)
If this assumption is correct, you can explain in detail why we get a compilation error
error: lvalue required as left operand of assignment
when we try to do
int (*test) (int a, int b) = malloc( 2*sizeof(*test)); test=diff;
Disclaimer: I believe this is a basic question and the assumption is true, but I would like a more detailed explanation so that this view is understandable to everyone.
Edit:
Please note that this is equivalent
int (*test) (int a, int b) = malloc( 2*sizeof(*test)); *test=*diff;
as this is somewhat more like a case:
int *test = malloc(2*sizeof(*test)); *test = 0; *(test+1) = 1;