Sunday, 11 November 2012

Function Pointers in C


//Program illustrates how function pointers are used to call various functions.

#include<stdio.h>
void apple(int x[3])
{
  int i;
  printf("\n From Function apple\n");
  for(i=0;i<3;i++)
  {
      printf("%d\t",x[i]);
  }
}

void ball(int x[3])
{
  int i;
  printf("\n From Function ball\n");
  for(i=0;i<3;i++)
  {
      printf("%d\t",x[i]);
  }
}

void cat(int x[3],void (*fp1)(int [3]))

/*cat is a function which receives a 1 Dimensional integer array and a function pointer as arguments*/
 
      printf("\n\n From function cat\n");
      (*fp1) (x);      /*Calling function pointed by function pointer fp1 with array x as argument*/
}

int main()
{

 int arr1[3]={111,222,333};
 int arr2[3]={444,555,666};

 void (*e[2]) (int [3]);
 /* 2 Function Pointers e[0] and e[1] which can point to a function with
     one Dimensional integer array as argument and returns void          */

  void (*fp) (int [3], void (*e) (int [3]) );
 /* Function Pointer fp which can point to a function with
     one Dimensional integer array and function pointer as arguments and returns void        */

   e[0]=apple;              /*function pointer e[0] points to function apple*/
   e[1]=ball;                 /*function pointer e[1] points to function ball   */
   fp=cat;                     /*function pointer fp points to function cat       */

   (*e[0]) (arr1);          /*caling function apple with array arr1 as argument*/
   (*e[1]) (arr2);          /*caling function ball with array arr2 as argument   */

   (*fp) (arr1,e[0]);      /*caling function cat with array arr1 and function pointer e[0] as arguments */
   (*fp) (arr2,e[1]);      /*caling function cat with array arr2 and function pointer e[1] as arguments */
   (*fp) (arr1,apple);
    /*caling function cat with array arr1 and function pointer using function name apple as arguments */
   (*fp) (arr2,ball);
    /*caling function cat with array arr2 and function pointer using function name ball as arguments    */
    return 0;
}


Click here to down load the C Program. 


No comments:

Post a Comment