Reputation: 55
I found somewhere this weird variable declaration -
float (*x[20])(int *a);
What could it possibly mean?
What is the purpose of it?
Upvotes: 0
Views: 3255
Reputation: 106092
float (*x[20])(*int a)
is not correct. It should be float (*x[20])(int *a)
which declares x
as an array of 20 pointers to a function that takes an argument of int *
type and returns float
.
For those who are curious to know the use of an array of function pointers:
typedef double Func(double, double); // Declare a double (double, double)
Func sum, subtract, mul, divide; // Function prototypes.
Func *p[] = { sum, subtract, mul, divide }; // Array of function pointers
int main(void)
{
double result;
double a, b;
int option;
printf("This is a simple calculator to add, subtract, multiply and divideide two integers\n");
printf("Enter two integers: ");
scanf("%lf %lf", &a, &b);
printf("Choose an option:\n 1. Add\n 2. Subtract\n 3. Mult\n 4. Divide\n");
scanf("%d", &option);
result = p[option - 1](a, b);
printf("result = %lf\n", result);
}
double sum(double a, double b) { return a+b; }
double subtract(double a, double b) { return a-b; }
double mul(double a, double b) { return a*b; }
double divide(double a, double b) { return a/b; }
A detailed explanation on how to read/decipher such complex declaration is discussed here.
Upvotes: 12
Reputation: 181
The code should be like this: - float (*x[20])(int *a);
- as (*int a)
seems to be incorrect. The code tells me that x is an array of 20 pointers to function that each takes an argument with datatype int and return float.
Upvotes: 0
Reputation: 11377
The declaration
float (*x[20])(int *a);
defines the variable x as an array of 20 functions (function pointers). In my humble opinion it's more clearly written as
Function x[20];
with
typedef float (*Function)(int *a);
The purpose of x is hard to tell without context, it could be to compute a statistical value like average, variance or standard deviation etc. given a set of integers and a function index input by the user:
x[0] = Average;
x[1] = Variance;
x[2] = StandardDeviation;
...
int a[100];
int i;
/*read data into `a' and function index into i...*/
printf("%f\n", x[i](a));
Upvotes: 1
Reputation: 1670
this is an array of function pointers. it has 20 function pointer items.
Upvotes: 1