Array of function pointers
Array of function pointer is nothing but an array whose elements are function pointers.
How to declare array of function pointer?
Below is an example declaration for array of function pointers.
int (*func[])(int, int);
Here, fun is an array of pointer to function (int, int) returning int
Example c program for array of function pointer
How to declare array of function pointer?
Below is an example declaration for array of function pointers.
int (*func[])(int, int);
Here, fun is an array of pointer to function (int, int) returning int
Example c program for array of function pointer
#include <stdio.h>
int add(int a, int b) {
return (a + b);
}
int sub(int a, int b) {
return (a - b);
}
int multiply(int a, int b) {
return (a * b);
}
int main() {
int (*fun[3])(int, int); // array of function pointers
int a = 20, b = 10, res;
/* assigning references for function pointers */
fun[0] = add;
fun[1] = sub;
fun[2] = multiply;
/* calling add() */
res = (*fun[0])(a, b);
printf("Addition of %d and %d is %d\n", a, b, res);
/* calling sub() */
res = (*fun[1])(a, b);
printf("Difference b/w %d and %d is %d\n", a, b, res);
/* calling multiply() */
res = (*fun[2]) (a, b);
printf("Product of %d and %d is %d\n", a, b, res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Addition of 20 and 10 is 30
Difference b/w 20 and 10 is 10
Product of 20 and 10 is 200
Addition of 20 and 10 is 30
Difference b/w 20 and 10 is 10
Product of 20 and 10 is 200
Write a c program to pass an array of function pointers to another function
#include <stdio.h>
int add(int a, int b) {
return (a + b);
}
int sub(int a, int b) {
return (a - b);
}
int multiply(int a, int b) {
return (a * b);
}
void manipulate(int a, int b, int (*fun[3]) (int, int)) {
int res;
/* calling add() */
res = (*fun[0])(a, b);
printf("Addition of %d and %d is %d\n", a, b, res);
/* calling sub() */
res = (*fun[1])(a, b);
printf("Difference b/w %d and %d is %d\n", a, b, res);
/* calling multiply() */
res = (*fun[2]) (a, b);
printf("Product of %d and %d is %d\n", a, b, res);
return;
}
int main() {
int (*fun[3])(int, int);
int a = 20, b = 10;
/* assinging references for function pointers */
fun[0] = add;
fun[1] = sub;
fun[2] = multiply;
/* passing array of function pointers as argument */
manipulate(a, b, fun);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Addition of 20 and 10 is 30
Difference b/w 20 and 10 is 10
Product of 20 and 10 is 200
Addition of 20 and 10 is 30
Difference b/w 20 and 10 is 10
Product of 20 and 10 is 200
Array of function pointers
Reviewed by Mursal Zheker
on
Rabu, Desember 25, 2013
Rating:
Tidak ada komentar: