What is a Function Pointer ?
Function Pointers are pointers, i.e. variables, which point to the address of a function. generally most of the text books give very brief tutorial for the concept of function pointer. it’s syntax is somewhat complicated. here is an attempt to simplify the things.
Consider below example:

#include<stdio.h>
int main()
{
   int a=8;
   int *p; /* here p is a pointer which will point */
           /*to an integer variable. but it requires an adress*/
           /*of integer variable for pointing*/

p = &a;  /* assign the address of a to pointer p */

printf("%x\t%d\n",a,*p);
return 0;
}

################################
output
################################
8 8

Lesson to learn from above example:
1) pointer is a variable.
2) pointer stores the address of another variable.
3) Like in above example a is variable which is assigned 8 and p is an integer pointer which strores the address of a.
4) to print the value at the pointer, * operator is used like in printf(“%x\t%d\n”,a,*p); statement.

The above example is very basic. so as p is called integer pointer, same way a pointer which points to an address of function called function pointer.

Syntax of declaration:

Return type (*name)(arguments);

Let us consider a plan function in C:

#include<stdio.h>
int add(int n, int m) {
    return n+m;
}
int main()
{
     add(3,4); // function call
}

if we want to declare a function pointer for above function int add(int n,int m) then the syntax will be
int (*fp)(int,int);
look at another example with function pointer declaration with “How to Use function pointer”

#include<stdio.h>
int add(int n, int m) {
    return n+m;
}
int main()
{
        int (*fp)(int, int); // declaration
        fp = add; // assign the address of function to function pointer (fp)
        int a= fp(3,4); // calling
        printf("%d\n",a);
}

How to Pass a Function Pointer as an Argument ?
consider below example.

#include<stdio.h>
void test() {
    printf("hello\n");
}
void abc(void (*a)()) {
    a();
}
int main() {
     abc(test);
     return 0;
}

For more exercise predict the output of below program.

>#include<stdio.h>
typedef struct{
    char* name;
    int green;
}Colors;
Colors color = {"green",0};
int p=0;
void print( Colors* (*fp)(void* a,int *b) )
{
    //struct Colors c1;
    int i = 5;
    Colors* c = fp((void*)&amp;color, &amp;i);
    i = i+++ 2;
        p = i;
}
Colors* giveName(void *a,int *b)
{
    Colors *ia = (Colors*)a;
    ia-&gt;name="green";
        *b = 6;
         return ia;
}
/*driver func*/
int main()
{
print(giveName);
printf("%d \n",p);
return 0;
}



Related Contents to follow