简体   繁体   中英

What this declaration “float (*x[20])(int *a)” means?

I found somewhere this weird variable declaration -

float (*x[20])(int *a); 

What could it possibly mean?
What is the purpose of it?

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 .

this is an array of function pointers. it has 20 function pointer items.

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM