Let's discuss briefly about Function pointers...
In C we know that each and every variable has got address. Similarly each and every function has an address associated with it. In order to know the address of the function
we use the following statement..
printf("Address of the function = %u",func); //func is some function.
So it is obvious that we can obtain the address of a function by specifying its name.
Now observe the statement below..
ptr = func;
Here func is the address of the function func. This address is being assigned to ptr.
Now the point is how do we declare ptr..
we declare it as...
(*ptr)();
Since ptr contains address it must be a pointer. In this case the pointer is containing the
address of the function so the declaration goes as (*ptr)() which says ptr is a pointer to a
function which does not have any arguments...
We will put all this discussion to work by considering an example...
#include<stdio.h>
int main()
{
int fun(int,int);
int (*ptr)(int,int);
printf("The address of the function is %u\n",fun);
ptr = fun;
(*ptr)(2,3);
}
int fun(int a,int b)
{
int res;
res = a+b;
printf("%d",res);
}
output: 5
Explanation : Here int (*ptr)(int,int) indicates that ptr is a pointer to a function which takes
two arguments and returns an integer. We can call the function fun by using the address of it. Thus a call is made to it by the statement (*ptr)(2,3)... The rest is
simple.
Advantage of Function pointers : The primary advantage with function pointer is that a function can be called at run time instead of compile time.



LinkBack URL
About LinkBacks
Reply With Quote
