ProAnswers.org

Declare an array of three function pointers where each function receives two integers and returns float ?

Declaration:
float (*fn[3])(int, int);

Program: Illustrates the usage of above declaration


#include<stdio.h>

float (*fn[3])(int, int);

float add(int, int);

int main() {

int x, y, z, j;

for (j = 0; j < 3; j++){

fn[j] = &add;

}

x = fn[0](10, 20);

y = fn[1](100, 200);

z = fn[2](1000, 2000);

printf("sum1 is: %d \n", x);

printf("sum2 is: %d \n", y);

printf("sum3 is: %d \n", z);

return 0;

}f

loat add(int x, int y) {

float f = x + y;

return f;

}

Output:

sum1 is: 30

sum2 is: 300

sum3 is: 3000

Explanation:

Here ‘fn[3]’ is an array of function pointers. Each element of the array can store the address of function ‘float add(int, int)’. fn[0]=fn[1]=fn[2]=&add Wherever this address is encountered add(int, int) function is called.