Pointer to function in C Language
Categories: C language
As we discussed in the previous chapter, a pointer can point to a function in C. However, the declaration of the pointer variable must be the same as the function. Consider the following example to make a pointer pointing to the function.
#include<stdio.h>
int addition ();
int main ()
{
int result;
int (*ptr)();
ptr = &addition;
result = (*ptr)();
printf("The sum is %d",result);
}
int addition()
{
int a, b;
printf("Enter two numbers?");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Enter two numbers?10 15
The sum is 25
Pointer to Array of functions in C
To understand the concept of an array of functions, we must understand the array of function. Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example.
#include<stdio.h>
int show();
int showadd(int);
int (*arr[3])();
int (*(*ptr)[3])();
int main ()
{
int result1;
arr[0] = show;
arr[1] = showadd;
ptr = &arr;
result1 = (**ptr)();
printf("printing the value returned by show : %d",result1);
(*(*ptr+1))(result1);
}
int show()
{
int a = 65;
return a++;
}
int showadd(int b)
{
printf("\nAdding 90 to the value returned by show: %d",b+90);
}
Output
printing the value returned by show : 65
Adding 90 to the value returned by show: 155