This blog is under construction

Wednesday, 23 October 2013

Function pointers

Pointer to function in c with examples:

What is function pointer?
Every function has an address.  We can assign the address of functions to pointers.  Then those pointers are called pointers to functions.  Pointers to function is also called as function pointers.

How to declare function pointer?
Below is the declaration of a function pointer.
        int          (  *func_ptr  )             (int)
  <return type> (* <pointer name> ) (argument type)
Here, "func_ptr" is a pointer to a function whose return type is integer and it takes an integer argument.

How to get the address of a function?
Address of a function can be obtained from the function name.  The below program illustrates how to print/get address of a function.


  #include <stdio.h>
  int add(int a, int b) {
        return (a+b);
  }

  int main() {
        printf("address of function add(): 0x%x\n", (int)add);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  address of function add(): 0x80483c4



How to initialize function pointer?
Function pointer can be initialized by assigning a function name to it.  The below program explains how to initialize function pointers.


  #include <stdio.h>
  /* finds the difference of given two numbers */
  int sub(int a, int b) {
        return (a - b);
  }

  int main() {
        int num1, num2, res;
        int (*fptr) (int, int); // function pointer declaration

        /* get the inputs from the user */
        printf("Enter your first number:");
        scanf("%d", &num1);
        printf("Enter your second number:");
        scanf("%d", &num2);

        /* assigning address of function to pointer */
        fptr = sub; // initializing function pointer

        /* invokes sub() function using function pointer */
        res = (*fptr)(num1, num2);

        /* printing the result */
        printf("Result: %d\n", res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first number:120
  Enter your second number:72
  Result: 48



How to invoke a function using function pointer?
Assign the address of a function to a pointer(function pointer).  Invoke the original function using the function pointer as shown below.  Pass arguments to function pointer if necessary.


  #include <stdio.h>

  /* prints hello world */
  void withoutArgs() {
        printf("Hello world\n");
        return;
  }

  /* prints the given string */
  void withArgs(char *str) {
        printf("%s\n", str);
        return;
  }

  int main() {
        void (*fptr_noArgs)(); // function pointer with no args
        void (*fptr_withArgs)(char *); // function pointer with args
        char str[] = "Hello Friend!!";

        /* function pointer initialization */
        fptr_noArgs   = withoutArgs;
        fptr_withArgs = withArgs;

        /* invoking functions using function pointers */
        (*fptr_noArgs)();  // no argument is passed
        (*fptr_withArgs)(str); // a string is passes as argument
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out 
  Hello world
  Hello Friend!!



How to pass function pointer as argument in c?
Assign address of a function to a pointer.  Pass the value of the function pointer as argument.  Below program explains how to pass function pointer as argument.


  #include <stdio.h>

  /* prints the result(sum of two numbers */
  void printMsg(int res) {
        printf("Sum of given two numbers is %d\n", res);
        return;
  }

 /* 
  * Adds the given number and prints the result.
  * Here, the third argument is pointer to function
  * and the parameter to function pointer is an integer
  */
  void add(int a, int b, void (*fptr)(int)) {
        int res = a + b;
        /* calling printMsg using function pointer */
        (*fptr)(res);
        return;
  }

  int main() {
        int num1, num2, res;

        /* get the inputs from the user */
        printf("Enter your first input : ");
        scanf("%d", &num1);
        printf("Enter your second input: ");
        scanf("%d", &num2);

        /*
         * passed the input values and 
         * address of the function "printMsg"
         * as argument
         */
        add(num1, num2, printMsg);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input : 105
  Enter your second input: 205
  Sum of given two numbers is 310



How to return a function pointer without typedef in c?
Just return the address of a function(function name or value of function pointer) as return value.  Below program explains how to return function pointer.  We haven't used any type definitions for function pointer in the below program.  But, usage of type definition in function pointer simplifies the codes and makes us easy to understand.


  #include <stdio.h>

  /* sum of two numbers */
  int add(int a, int b) {
        return (a + b);
  }

  /* difference of two numbers */
  int sub(int a, int b) {
        return (a - b);
  }

  /* product of two numbers */
  int multiply(int a, int b) {
        return (a * b);
  }

  /* division of two numbers */
  int divide(int a, int b) {
        return (a / b);
  }

  /*
   * choice() is a function that takes an integer argument(ch)
   * and returns a function pointer.  The returned 
   * function pointer takes two integer arguments and returns
   * an integer value
   */
  int (*choice(int ch))(int , int) {
        switch (ch) {
                case 1:
                        return (add);
                case 2:
                        return (sub);
                case 3:
                        return (multiply);
                case 4:
                        return (divide);
        }
  }

  int main() {
        int num1, num2, ch, res;
        int (*fptr)(int, int); // function pointer declaration

        /* get the inputs from the user */
        printf("Enter your first input: ");
        scanf("%d", &num1);
        printf("Enter your second input: ");
        scanf("%d", &num2);

        /* get the choice from the user */
        printf("1. Add\t2. Sub\n");
        printf("3. Multiply\t4.Divide\n");
        printf("Enter your choice:");
        scanf("%d", &ch);

        /* choice is a function returns function pointer */
        fptr = choice(ch);

        /*
         * calls add/sub/multiply/divide based on
         * the value of function pointer
         */
        res = (*fptr)(num1, num2);
        printf("Result is %d\n", res);
        return 0;
  }



How to return a function pointer with typedef?
Below program explains how to return a function pointer using type definitions.


  #include <stdio.h>
  /*
   * type definition for function pointer that takes
   * two integer arguments and returns an integer
   */
  typedef int (*fptr)(int, int);

  /* returns sum of two numbers */
  int add(int a, int b) {
        return (a + b);
  }

  /*
   * function returning function pointer
   * fptr - is the typedef for function pointer
   */
  fptr wrapper() {
        return (add);
  }

  int main() {
        int num1 = 10, num2 = 20, res;
        fptr func_ptr; // function pointer declaration

        /* wrapper() returns address of add() api */
        func_ptr = wrapper();
        /* calling add() using function pointer */
        res = (*func_ptr)(num1, num2);

        /* printing the result */
        printf("Sum of %d and %d is %d\n", num1, num2, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Sum of 10 and 20 is 30



How to declare function pointers as structure member?
Function pointers can be declared as structure member like other normal variables.  Below code snippet gives clear idea on how to declare function pointer as structure member.

  struct mathOps {
       int val1, val2;
       int (*add) (int, int);  // function pointer takes two int args and returns an integer
       int (*sub) (int, int);  
       void (*print) (char *); // function pointer takes a character pointer as argument
  };


How to invoke function pointers defined in a structure?
Below program explains how to invoke function pointer defined inside a structure.


  #include <stdio.h>
  #include <stdlib.h>
  /* structures with function pointer as its member */
  struct msg {
        void (*printMsg)(char *);
  };

  struct mathOp {
        int (*add)(int, int);
  };

  /* prints the given message */
  void printMessage(char *str) {
        printf("%s\n", str);
        return;
  }

  /* adds the given two numbers */
  int addTwoNum(int a, int b) {
        return (a + b);
  }

  int main() {
        char str[128];
        struct msg m1; // structure object
        struct mathOp *op;  // pointer to a structure
        int num1 = 10, num2 = 20, res;

        /* dynamic memory allocation */
        op = (struct mathOp *) malloc(sizeof(struct mathOp));

        /* function pointer initialization */
        m1.printMsg = printMessage;
        op->add = addTwoNum;

        /* calling addTwoNum() using function pointer */
        res = op->add(num1, num2); // -> operator is used since op is ptr

        /* storing output in a string */
        sprintf(str, "Sum of %d and %d is %d", num1, num2, res);

        /* calling printMessage() using function pointer */
        m1.printMsg(str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/pointers$ ./a.out
  Sum of 10 and 20 is 30




How to cast void pointer to function pointer in c?
Below code snippet explains how to typecast void pointer to function pointer.
  int add(int, int); // function
  int (*func)(int, int);  // function pointer
  void *ptr;  // void pointer
  ptr = add  // assigning address of a function to void poiter
  func = (int (*)(int, int)) ptr; // type casting void pointer to function pointer
  (*func)(a, b);  // invoking add() using function pointer

Finally, we have done typecasting void pointer to function pointer.


  #include <stdio.h>
  /* adds given two numbers */
  void add(int a, int b) {
        printf("Sum of %d and %d is %d\n", a, b, (a + b));
  }

  int main() {
        void *ptr;  // void pointer
        void (*fptr)(int, int);  // function pointer

        ptr = add;  // assigning value to void pointer

        /* typecasting void pointer to function pointer */
        fptr = (void (*)(int, int))ptr;

        /* calling add() using function pointer */
        (*fptr)(100, 300);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Sum of 100 and 300 is 400


How to declare array of function pointers in c?
int (*func_ptr[])();
Here, func_ptr is an array of pointer to a function returning integer.

Typedef is usually used to simplify complex pointer declarations.  The above can also be written as follows.
typedef int (*func_ptr) ()
func_ptr fptr[];
Here, fptr is an array of pointer to function returning integer.

No comments:

Post a Comment