Following is the array of function pointers
(int) (*a[5]) (int);
int f1(int){};
...
is the following way of definition correct?
a = f1;
a + 1 = f2;
a + 2 = f3;
...
how do we call these functions?
*a(1) // is this correct???
*(a+1) (2)
#include <stdio.h>
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
int (*a[5]) (int);
a[0] = f1;
a[1] = f2;
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
}
a return 0; /* Or something */ before the final }.What you call "definition" is just assignment, and as you are doing it, it is wrong, since you can't assign to arrays in C. You can only assign to individual array elements, correct would be a[0] = f1 etc.
Often for arrays of function pointers there is no need to assign them dynamically at run time. Function pointers are compile time (or link time) constants anyhow.
/* in your .h file */
extern int (*const a[5]) (int);
/* in your .c file */
int (*const a[5]) (int) = { f1, f2, f3 };
To simplify using function pointers a bit, the identifier for a f1 is equivalent to a pointer to the function &f1 and using a function pointer with parenthesis as in a[0](5) is the same as dereferencing the pointer and calling the resulting function (*(a[0]))(5).
int (*fp)(int), fp(5) and (*fp)(5) are equivalent. There is nothing to "understand" here, this is just a short cut defined by the C language.It is always better to use typedefs, (and all your functions need to have a common interface anyway and also to initialise at declaration time, where possible function arrays should also be const as a safety measure so:
#include <stdio.h>
typedef int (*mytype)();
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
const mytype a[5] = {f1,f1,f2,f2,f1};
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
return 0;
}
#include<stdio.h>
int (*a[5]) (int);
int f1(int i){printf("%d\n",i); return 0;}
int f2(int i){printf("%d\n",i); return 0;}
int f3(int i){printf("%d\n",i); return 0;}
int main(void)
{
a[0] = f1; // Assign the address of function
a[1] = f2;
a[2] = f3;
(*a[0])(5); // Calling the function
(*a[1])(6);
(*a[2])(7);
getchar();
return 0;
}
rvaluewhere it expected anlvalue???