Programming in C: Unit III (b): Pointers

Array of Function Pointers

with Example C Program

When an array of function pointers is made, the appropriate function is selected using an index. The code given below shows the way to define and use an array of function pointers in C.

ARRAY OF FUNCTION POINTERS

When an array of function pointers is made, the appropriate function is selected using an index. The code given below shows the way to define and use an array of function pointers in C.

Step 1: Use typedef keyword so that 'fp' can be used as type

typedef int (*fp) (int, int);

Step 2: Define the array and initialize each element to NULL. This can be done in two ways:

// with 10 pointers to functions which return an int and take two ints

1. fp funcArr [10] = {NULL};

2. int (*funcArr [10]) (int, int) = {NULL};

Step 3: Assign the function's address-'Add' and 'Subtract' funcArr1 [0] = funcArr2[1] = Add;

funcArr [0] = &Add;

funcArr [1] = &Subtract;

Step 4: Call the function using an index to address the function pointer

printf("%d\n", funcArr [1] (2, 3));

// short form

printf("%d\n", (*funcArr [0]) (2, 3));

// correct way

30. Write a program to add, that uses an array of function pointers, subtract, multiply, or divide two given numbers.

#include <stdio.h>

int sum (int a, int b);

int subtract (int a, int b);

int mul (int a, int b);

int div (int a, int b);

int (*fp [4]) (int a, int b);

int main (void)

{

int result;

int num1, num2, op;

fp [0] = sum;

fp [1] = subtract;

fp [2] = mul;

fp [3] = div;

printf("\n Enter the numbers: ");

scanf("%d %d", &num1, &num2);

do

printf("\n 0: Add \n 1: Subtract \n 2: Multiply \n 3: Divide \n 4. EXIT\n");

printf("\n\n Enter r the operation: ");

scanf("%d", &op);

result (*fp [op]) (num1, num2);

printf("\n Result = %d", result);

} while (op!=4);

return 0;

}

int sum (int a, int b)

{

return a + b;

}

int subtract (int a, int b)

{

return a - b;

}

int mul (int a, int b)

{

return a* b;

}

int div(int a, int b)

{

if (b)

return a / b;

else

return 0;

}

Output

Enter the numbers: 2 3

0: Add

1: Subtract

2: Multiply

3: Divide

4. EXIT

Enter the operation: 0

Result = 5

Enter the operation: 4

Programming in C: Unit III (b): Pointers : Tag: : with Example C Program - Array of Function Pointers