C function pointer



What is function Pointer ?

Function pointer : A pointer which keeps address of a function is known as function pointer. [ Visit : Complete Reference Document for Function Pointer ]


Live Example :

#include<stdio.h>

void display();

int main()
  {
  void *(*ptr)();
  ptr = &display;
  (*ptr)();

  return(0);
  }

void display()
{
printf("Hello World");
}

Output :

Hello World

Explanation of C Snippet :

Consider normal program –

Now in the above program we have just called function display(), and we get output as “Hello World”.


Consider Scenario using pointer , We should follow following 3 steps to use pointer to call function –

  1. Declare Pointer which is capable of storing address of function.
  2. Initialize Pointer Variable
  3. Call function using Pointer Variable.

Step 1 : Declaring Pointer

void *(*ptr)();
  • We are simply declaring a double pointer.
  • Write () symbol after “Double Pointer“.
  • void represents that , function is not returning any value.
  • () represents that , function is not taking any parameter.

Above declaration tells us ….

Declare Pointer variable that can store address of function which does not return anything and doesn’t take any parameter

Step 2 : Initializing Pointer

ptr = &display;

This statement will store address of function in pointer variable.

Step 3 : Calling a function

(*ptr)();

using (*ptr)() we can call function display();

(*ptr)() = (*ptr)();
         = (*&display)();
         = (display)();
         = display();

thus (*ptr)() is as good as calling function.

Requirement Declaration of Function Pointer Initialization of Function Pointer Calling Function using Pointer
Return Type : None
Parameter   : None
void *(*ptr)();
ptr = &display;
(*ptr)();
Return Type : Integer
Parameter   : None
int *(*ptr)();
ptr = &display;
int result;
result = (*ptr)();
Return Type : Float
Parameter   : None
float *(*ptr)();
ptr = &display;
float result;
result = (*ptr)();
Return Type : Char
Parameter   : None
char *(*ptr)();
ptr = &display;
char result;
result = (*ptr)();

Example 1 : Function having two Pointer Parameters and return type as Pointer

#include<stdio.h>

char * getName(int *,float *);

int main()
{
char *name;
int  num = 100;
float marks = 99.12;

char *(*ptr)(int*,float *);
ptr=&getName;
name = (*ptr)(&num,&marks);

printf("Name : %s",name);

return 0;
}
//-------------------------------------
char *getName(int *ivar,float *fvar)
{
char *str="www.c4learn.com";
str = str + (*ivar) + (int)(*fvar);
return(str);
}

Output :

.c4learn.com