How can I use an array of function pointers? How can I use an array of function pointers? c c

How can I use an array of function pointers?


You have a good example here (Array of Function pointers), with the syntax detailed.

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 (*p[4]) (int x, int y);int main(void){  int result;  int i, j, op;  p[0] = sum; /* address of sum() */  p[1] = subtract; /* address of subtract() */  p[2] = mul; /* address of mul() */  p[3] = div; /* address of div() */[...]

To call one of those function pointers:

result = (*p[op]) (i, j); // op being the index of one of the four functions


The above answers may help you but you may also want to know how to use array of function pointers.

void fun1(){}void fun2(){}void fun3(){}void (*func_ptr[3])() = {fun1, fun2, fun3};main(){    int option;    printf("\nEnter function number you want");    printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */    scanf("%d",&option);    if((option>=0)&&(option<=2))    {         (*func_ptr[option])();    }    return 0;}

You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.

You can also pass arguments like below if all the above functions are having the same number of arguments of same type.

  (*func_ptr[option])(argu1);

Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1 can be called if option=0, fun2 can be called if option=1 and fun3 can be called if option=2.


Here's how you can use it:

New_Fun.h

#ifndef NEW_FUN_H_#define NEW_FUN_H_#include <stdio.h>typedef int speed;speed fun(int x);enum fp {    f1, f2, f3, f4, f5};void F1();void F2();void F3();void F4();void F5();#endif

New_Fun.c

#include "New_Fun.h"speed fun(int x){    int Vel;    Vel = x;    return Vel;}void F1(){    printf("From F1\n");}void F2(){    printf("From F2\n");}void F3(){    printf("From F3\n");}void F4(){    printf("From F4\n");}void F5(){    printf("From F5\n");}

Main.c

#include <stdio.h>#include "New_Fun.h"int main(){    int (*F_P)(int y);    void (*F_A[5])() = { F1, F2, F3, F4, F5 };    // if it is int the pointer incompatible is bound to happen    int xyz, i;    printf("Hello Function Pointer!\n");    F_P = fun;    xyz = F_P(5);    printf("The Value is %d\n", xyz);    //(*F_A[5]) = { F1, F2, F3, F4, F5 };    for (i = 0; i < 5; i++)    {        F_A[i]();    }    printf("\n\n");    F_A[f1]();    F_A[f2]();    F_A[f3]();    F_A[f4]();    return 0;}

I hope this helps in understanding Function Pointer.