Friday, 27 March 2015

Pointer to a function/Function pointer

In c we can use pointer to point to function also. It's similar to a pointer to a int or char or a struct. when we declare pointer to a function it points to a code sitting in a memory for a function. following example shows the use of function pointer

#include <stdio.h>

// Simple function to add 2 number
int sum(int x, int y){
        return x+y;
}

// use of typedef to declare a function pointer 
typedef int (*funct_ptr)(int a , int b);



int main(){
        int (*ptr)(int,int);   // deceleration of  function pointer 
        ptr = &sum;          // Initialize the pointer to point to a function sum
        funct_ptr ptr1;      // this will show how to use typedef to declare pointer variable.
        int sumation;
        sumation = (*ptr)(3,4);    // call the function using pointer 
        printf("sum is %d \n",sumation);
        ptr1 = sum;                     //  Second type of call for a function pointer
        sumation = ptr1(3,5);
        printf("sum is %d \n",sumation);
        return 0;
}


Output:

sum is 7
sum is 8

Another example of function pointer is as mentioned below. Function pointer can be used inside a structure to access the data member of a structure. By default C does not support Function inside a structure.

#include <stdio.h>
#include <stdlib.h>

typedef void (*fp_set)(int, int, int);
typedef long (*fp_cal)();

struct volume
{
int h;
int b;
int l;
fp_set setval;
fp_cal calvol;
};
typedef struct volume vol;
static vol v;

void set(int a, int b , int c)
{
v.h = a;
v.b = b;
v.l = c;
}

long cal()
{
return v.h*v.b*v.l;
}

int main()
{
v.setval= set;
v.calvol = cal;

v.setval(4,5,6);
printf("volume is %ld \n",v.calvol());

return 0;
}

Output:

volume is 120