Function Pointer

We can create a pointer of any data type such as a int, char, float. As opposed to referencing a data value function pointer points to executable code within memory. Function pointers points to code not data, typically a function pointer stores the start of executable code.

Syntax of function pointer

return type(*ptr_name)(type1,type2,type3......);

For example

int(*ip)(int);

float(*fp)(float);

In the above declaration *ip and *fp is a pointer that points to a function which returns an int and float value and accepts integer and float
value an argument.

Let’s see the example

#include <stdio.h>  
int main()  
{  
    printf("Address of main() function is %p",main);  
    return 0;  
}

Output

address of main() function is 0x400536

......Program finished with exit code 0
Press ENTER to exit console.

Calling function through a function pointer

We will see how to call a function using function pointer.we declare a function given below

float func(int, int);

Calling above function using a usual way

total=func(a,b);

Calling function using function pointer

total=(*fp)(a,b);

Why we use function pointer ?

  • We can use function pointer to avoid code redundancy and not only this with the function pointers and void pointers it is possible to use qsort for any data type.
  • We do not allocate de-allocate memory using function pointers.
  • In the function pointer a function name can also be used to get functions address.
  • Function pointer can be used in place of switch case.

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews