Saturday 11 October 2014

Function Pointer

( * Function Pointer )


Hello Friends,
Today I am going to discuss about function pointer.

OVERVIEW :

What is Pointer to function?

Just like pointer to variable, pointer to array and pointer to structure, we can also have pointer to function. We can say that function will be stored somewhere inside memory and we can declare pointer to that function.

DECLARATION :

We can declare function pointer same as declaration of simple function. Suppose we have function add() which takes int a and int b as parameters and it returns integer value. And we want to declare pointer to this function. So we can do it this way :

suppose function is,

int add(int a,int b)
{
      return a+b;
}

and now we will declare pointer to this function . . .

void main()
{
      int (*ptr_func) ( int , int );

      ptr_func = &add;
// this will also work
      ptr_func = add;
}

steps to create function pointer :
1) first of all write return type of function. -> int
2) then write name of pointer in '( )' -> int (*ptr_func)
3) then write type of arguments -> int (*ptr_func) (int,int)

Third step is not necessary so we can also write
int (*ptr_func) ( )
but it's a good habit to write argument types.

PROGRAMs on function pointer:

Now let's see some programs on function pointer.

1). Passing function as a parameter

#include <stdio.h>

int add(int a,int b,void (*ptr2) ( ) )
{
       ptr2( );                             //calling func
       return a+b;
}
void func()
{
       printf("Addition !!\n");
}
void main()
{
       int ans;
       int (*ptr1) ( ) = add;                      //pointer to function add
       ans = ptr1( 3 , 4 , func );               //passing func as parameter
       printf( " ANS : %d \n ", ans );
}

o/p :
Addition !!
ANS : 7

Explanation :

This was a very simple example to understand passing of function as a parameter.

But here you may have one question. Why do we need to pass function as a parameter?
Because in this program use of function pointer doesn't make sense. best example for this is library function qsort(). 

For small program like this, this seems to be unnecessary.

2). we can made array of pointer to function.

Before going for this program let's see another one.

This is program for simple calculator.

#include <stdio.h >

int add (int a , int b) { return a+b; }
int sub (int a , int b) { return a-b; }
int mul (int a , int b) { return a*b; }
int div (int a , int b) { return a/b; }

void main()
{
   int input, ans;
   printf("1. Add \n 2. Substract \n 3. Multiply \n 4. Divide \n 5. Exit \n Enter Your Choice : ");
   scanf("%d",&input);

   switch(input)
  {
     case 1:
        ans = add( 3 , 4 );
        break;

     case 2:
        ans = sub ( 3 , 4 );
        break;
     
     case 3:
        ans = mul ( 3 , 4 );
        break;

     case 4:
        ans = div( 3 , 4 ); 
        break;

     default:
         break;
 }

 printf(“ANS : %d \n ”, ans );

}

Now let's use array of function pointer for the same program.

#include <stdio.h >

int add (int a , int b) { return a+b; }
int sub (int a , int b) { return a-b; }
int mul (int a , int b) { return a*b; }
int div (int a , int b) { return a/b; }

void main()
{
    int input, ans;
    int (*ptr_fun [4] ) ( int , int ) = { add, sub, mul, div };

    printf("1. Add \n 2. Substract \n 3. Multiply \n 4. Divide \n 5. Exit \n Enter Your Choice : ");
    scanf(" %d ", &input );

    ptr_fun [input-1] ( 3 , 4 ); //replacing whole switch case !!!
}

Just like array of pointer we have array of pointer to function.
So this way we can replace switch case with only a single line.


  • typedef WITH FUNCTION POINTER :

As we know typedef is used for simple naming convention, we can use it for function pointer to make it more easy to read. When we have more than one function having same return type and same parameters we can make a simple way of declaring pointer to this function.

Suppose we want pointer to function for all functions add, sub, mul and div , we can do it like this,

int (*ptr1_fun) (int, int) = add;
int (*ptr2_fun) (int, int) = sub;
int (*ptr3_fun) (int, int) = mul;
int (*ptr4_fun) (int, int) = div;

now let's make it simple using typedef.

typedef int (*ptr_fun ) ( int , int);

now we can use ptr_fun to declare new pointers to function having return type integer and both parameters also integer.

ptr_fun ptr1 =add;
ptr_fun ptr2 = sub;
ptr_fun ptr3 = mul;
ptr_fun ptr4 = div;


OHH!! It looks very clean.

Thanks,
Akash Patel

Are you a Fresh Programmer?? Join facebook group to be a perfect programmer.
https://www.facebook.com/groups/121611948548929/

Link for Pointer in C :
http://letsmakeceasy.blogspot.in/2014/09/pointer-in-c.html

Link for Array in C :
http://letsmakeceasy.blogspot.in/2014/09/array-in-c.html

Link for Preprocessor in C :
http://letsmakeceasy.blogspot.in/2014/09/preprocessor-directives.html
  

Thursday 2 October 2014

Tricky C Programs

Hello friends,

Here i have given some basic programs to understand pointer to array and pointer to string.
copy each and run it on your machine one bye one and see the difference between each of them.

1. Array with Pointer
* Predict the output of following programs.

1.1
main()
{
int arr[]={10,20,40,50,45};
int i;
for(i=0;i<5;i++)
printf("%d ",*(arr+i));
}
-------------------------------------------------------------------
many people have question, what is the difference between array name and pointer to that array?
Run program 1.2 and 1.3 and get the answer by your self.

1.2
main()
{
int arr[]={10,20,40,50,45};
int i;
for(i=0;i<5;i++)
printf("%d ",*(arr++));
}
-------------------------------------------------------------------
1.3
main()
{
int arr[]={10,20,40,50,45},*ptr;
int i;
ptr = arr;
for(i=0;i<5;i++)
printf("%d ",*(ptr++));
}
--------------------------------------------------------------------
1.3 and 1.4 shows the importance of bracket ' ( ) ' .

1.4
main()
{
int arr[]={10,20,40,50,45},*ptr;
int i;
ptr = arr;
for(i=0;i<5;i++)
printf("%d ",(*ptr)++);
}
---------------------------------------------------------------------
1.5
main()
{
int arr[]={10,20,40,50,45},*ptr;
int i;
ptr = arr;
for(i=0;i<5;i++)
printf("%d ",*ptr++);
}

--------------------------------------------------------------------------------------------------

2. String and Pointer :

2.1
void main()
{
char arr[] = "hello world !!!";
printf("%s\n",arr);
}
------------------------------------------------------------------------
2.2
void main()
{
char *ptr;
ptr = "hello world !!!";
printf("%s\n",ptr);
}
------------------------------------------------------------------------
2.3
void main()
{
char *ptr;
scanf("%s",ptr);                             // input any string.
printf("%s\n",ptr);
}
------------------------------------------------------------------------------------------
In program 2.3 you will get segmentation fault during run time. why?

because when you compile your program compiler decides howmuch space this program will require for execution and for storing variables and all.

In 2.1 and 2.2 compiler automatically calculates the space for given string because the string is already given. but in 2.3,we are entering string during run time and compiler didn't give us any space to store our string. so during run time it gives segmentation fault. In this case we have to use dynamic memory allocation. see example 2.4....
------------------------------------------------------------------------------------------
2.4
void main()
{
char *ptr; = (char *)malloc(5*sizeof(char));
scanf("%s",ptr);                             //  input "hello" or any string with max 5 char.
printf("%s\n",ptr);
}
----------------------------------------------------------------------

i think, these programs are enough to understand pointer to array and pointer to string.
for any query or explanation please use comment box.

Are you a Fresh Programmer?? Join facebook group to be a perfect programmer.
https://www.facebook.com/groups/121611948548929/

Link for Pointer in C :
http://letsmakeceasy.blogspot.in/2014/09/pointer-in-c.html

Link for Array in C :
http://letsmakeceasy.blogspot.in/2014/09/array-in-c.html

Link for Preprocessor in C :
http://letsmakeceasy.blogspot.in/2014/09/preprocessor-directives.html

Thanks
Akash Patel.