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. 

Monday 29 September 2014

Array in C

ARRAY [ ]

Hello friends,
Today I am going to discuss Array in programming C.

Overview :

C language provides facility to design set of similar data types called array. So, what is array ?
Array is group of variables of same datatypes. When we need multiple variable of same datatype, array can be used.

Array :

Suppose you are collecting percentage marks of 100 student. Then there are two possibility.
1) we take 100 variable to store percentage marks of 100 student.
or 2) we take single variable named marks, which is capable to store all 100 percentage marks of 100
    Students.

obviously second one is better. Because in first case if we want to sort or one by one access the value of marks of each student then it will become very hard task to do. But if we use array here than it becomes easy. Let’s see how?

How to declare array ?

int mark[100];

here we create array of 100 variable of type integer. And mark is name of that array.

we can expand mark[100] like this :
mark[0], mark[1], mark[2] ….. ,mark[99].

Value written within bracket “[]”  shows number of element. 100 is number of element in our case.
note that array position starts with 0th location.

let’s make array smaller to take some example. I am taking array to store marks of 5 student. Then I will declare array as,

int mark[5].

now how to scan and print array element ?
For that we have to take another integer variable as index value of array.

int i;
for(i=0 ; i<5 ; i++)
scanf(“ %d ” ,&mark[i]);

Now take random marks, 10 20 40 55 35.

for(i=0 ; i<5 ; i++)
printf(“student%d = %d\n”,i+1,mark[i]);

o/p :
student1 = 10;
student2 = 20;
student3 = 40;
student4 = 55;
student5 = 35;

so if we want to get value of third element from the array into variable z, we can get it by,
z = mark[2];

note: here I am writing 2 and not 3. Because mark[0] is first element of array. So, mark[2] becomes third element.

Another way of Declaration :

We can assign value to array at declaration time too.
int mark[5] = {10, 20, 40, 55, 35};

Note that if we are assigning value at declaration time, it doesn’t require to give size of array. What I am saying is, we can write above statement as,
int mark[] = {10, 20, 40, 55, 35};

but if you are not assigning value at declaration time than we have to specify the length of array. Because we have to tell compiler that howmany value i am going to store in my array and according to that compiler will give use memory space.

note that array elements are stored in contiguous memory location.

If we are taking array with 8 element (ex. Mark[8]) and we assign value upto 5th element, but we are printing value of array till 8th position. Than what will be printed for 6th, 7th and 8th element ?
Answer : it will print any garbage value. Or zero in most of case.

char array :

char arr[]={‘a’ , ‘b’, ‘c’, ‘d’, ‘e’};

declaration is same as integer array, but when we are giving character value to array we have to write character in single quotation.

Array for string :

we can also assign whole string to array.

Char arr[] = “Hello_World”;

How this string appears in array ? -> { ‘H’, ’e’, ‘l’, ‘l’, ‘o’, ‘_’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ };

Look at the last element. ‘\0’ is called null character. It is here to indicate the end of string.

Now lets see example for this,

main()
{
            char arr[10];
            printf(“Enter String : ”);
            scanf(“%s”,arr);

            printf(“\n string entered by user : %s ”,arr);
}

o/p:
Enter String : hello
String entered by user : hello

Here in scanf we have used arr and note &arr.
Because by adding ‘&‘ , we gets the address of variable where we want to store our data.
ex.  
     int a;
     scanf(“ %d ”, &a);

here ‘ &a ’ is address of variable a. (you will understand this easily once you learn pointer.).
back to our program, array name is pointer to the first element of array or string. So in our case arr is pointer to ‘h’ or we can say arr has address of ‘ h ’. so as per low second argument of scanf should be address and in our case “ scanf(“ %s ”,arr) “  arr itself is address.


Passing array to Function :

How to pass array to function ?

Let’s take same array mark[5] having value 10, 20, 40, 55, 35. And we are passing it to add function which will add all element of array. So we have to pass full array and length of array.

#include<stdio.h>

int add(int arr[], int);
main()
{
            int mark[] = {10, 20, 40, 55, 35};
            int ans;
            ans = add(mark,5);
            printf(“Ans = %d\n”, ans);
}
int add(int arr[],int len)
{
            int i,num = 0;
            for(i = 0 ; i <len ; i++)
            {
                        num = num + arr[i];
            }
            return(num);
}

o/p :
Ans = 160.

To understand what we are doing here, you should be aware with pointer. Array is similar to pointer. Array name itself is pointer to first element of array. So we can pass only array name to the function and function will get the address of first element of passed array and as you know array elements are stored in contiguous location, function can access full array.

Don’t get confused. If you are unable to understand this than leave it. First understand pointer to array and than again read above lines. I will give link for pointer to array at the end of discussion.

Now let me take another example.
Now we will change the value of second element of array in called function and then we will check whether the second element of mark array in main function is changed or not.

#include<stdio.h>

void func(int arr[], int);
main()
{
            int mark[] = {10, 20, 40, 55, 35};
           
            printf(“second element = %d before \n”, mark[1]);
add(mark,5);                                                    //calling a function
            printf(“second element = %d after \n”, mark[1]);
}
Void func(int arr[],int len)
{
            arr[1] = arr[1] + 10;
}

Run this program and you will get second element becomes 30 from 20.

o/p :
second element = 20 before
second element = 30 after

value is changed because we are not passing value of array element, but we are passing address of array element.

So array is all about pointer and address.

At this stage i am going to stop this discussion on array. Still many thing remains in array part. I will update my blog soon.


If anyone have query, question or suggestion please write it bellow in the comment box.

To know more on another important topic in c “POINTER

To know more on another important topic in c “C PREPROCESSOR

Are you a Fresh Programmer?? Join facebook group to be a perfect programmer.

https://www.facebook.com/groups/121611948548929/

Thanks,

Akash Patel.


Sunday 28 September 2014

Pointer in C

*POINTER 

Hello Friends,
Today I am going to discuss one of the most most important and sometimes very difficult topic in C,  Yeah It's “POINTER”.

TOPICS COVERED :
What is Pointer?
Call by Value & Call by Reference
Pointer to Array
Pointer to String
Pointer to Structure
Pointer to Function (or Function Pointer)

Now let's start with overview of Pointer.


OVERVIEW :

For any C beginner, the most difficult word to understand is “Pointer”. But Trust me, It is must to learn pointer for every pointer. Because once you understand pointer, your 90% job is finished. Now let’s start with this magical word “Pointer”.


POINTER :

What is pointer ?
As name suggest pointer means point to some location. Pointer is a variable that contains the address of another variable. We can have a pointer to any variable type.

Pointer Notation :

How to use pointer ?

int a = 3;

When we initialize any type of variable, it gets memory in stack in the system. Now in pointer variable we will store the address of that variable. But before that how to declare a pointer? it’s same as declaration of any type of variable.

int *ptr;                       // pointer declaration

datatype of pointer is datatype of variable, whose address is going to be stored in pointer. Now how to assign address to pointer? If we use ‘&’ before any variable it gives address of that variable.

ptr = &a;

Suppose value at variable a is 3, and its address is 65223. So now value of ptr is address of a.

a = 3;                          // value of a
&a = 65223;                 // address of a
ptr = 65223;                 // value of ptr.

And here our pointer variable ptr will also have its own address where it has stored. So we can store it into another pointer variable. And it becomes double pointer. To declare a double pointer we need add one more star before pointer name.

int **ptr1;

ptr1 = &ptr;

suppose address of ptr is 65400, so the value of ptr1 is 65400.

Now let me clear, what’s going on .












Please see the picture again and again. If you will understand this then that’s it. Here ptr1 has its own address and we can store it in another pointer variable and it becomes triple pointer(***ptr2) and so on….

NOTE : Many times interviewers ask questions on pointer, double pointer and triple pointer to confuse interviewees. So always be clear with this concept before going to any C based interview.

what is call by value and call by reference? or
what is the difference between call by value and call by reference ?

CALL BY VALUE:

I hope you are aware with function. Here I am going to write a simple function to increment variables, but without using pointer.

#include<stdio.h>
void func(int , int);    //Function Declaration

void main(void)
{
            int a=2, b=3; 

            func(a, b);

            printf(“ a=%d\n b=%d\n”, a, b);
}
void func( int x, int y )
{
            ++x;                  // Increment first variable('x')
            ++y;                  // Increment second variable('y')
}

O/P :
a = 2;
b = 3;
----------------------------------------------------------------------------
Note : Here we have changed 'x' and 'y' but 'a' and 'b' are still unchanged.


CALL BY REFERENCE :

Now I am writing the same program, but using pointer. So instead of passing values of variables a and b, I will pass addresses of variables a and b.

#include<stdio.h>
void func(int *, int *);    // Function Declaration

void main(void)
{
            int a=2, b=3;
            
            func( &a , &b );
            
            printf(“ a = %d\n b = %d\n”, a, b);
}
void func( int *x, int *y )
{
            ++(*x);       //Increment first variable(this time not 'x' but 'a' of main())
            ++(*y);       //Increment second variable(this time not 'y' but 'b' of main())
}

O/P :
a = 3;
b = 4;

Yeah... That Call a Magic !!!!!


Here we are passing addresses of a and b, so we have used '&a' and '&b'. As we are passing addresses, we have to declare x and y as pointers. So we have used int *x and int *y.

And see the magic, we have changed values of *x and *y inside a function and it reflects to a and b in our main function because x and y contain addresses of a and b respectively and *x and *y are values on that addresses. So indirectly ++(*x) & ++(*y) increment a and b respectively. 

You may have noticed that this way by using pointers we can return multiple values from the function.

What is the benefit of using call by reference ?

The Answer is, when we pass address, Program doesn’t need to do any read/write operations like what it needs to perform in call by value, where we have to read variable, store it in cpu register, write it into another memory location of variable in called function and then we will do some operation on that value and at the end we have to return answer to calling function. And in call by reference, these operations will not happen.
So, we can increase the speed of operation of our application by using pointer mechanism. But this is not the only benefit. There are so many benefits but those you will get by doing more and more programs

How to print address of variable?
void main(void)
{
int i = 3 ;
printf ( "\nAddress of i = %u", & i  ) ;              // %u for printing address.
printf ( "\nValue of i = %d", i ) ;
           printf ( “\nValue of i = %d”, *(& i ));
}  
o/p:

Address of I = 65223
Value of I = 3.
Value of I = 3.

-----------------------------------------------------------------------------------------------------
POINTER TO ARRAY :

int arr[5]={1,2,3,4,5};
int *ptr

ptr = &arr[0];   or ptr = arr;

statement 1 : printf ( “ %d %d %d %d %d ” , arr[0], arr[1], arr[2], arr[3], arr[4]);

statement 2 : printf ( “ %d %d %d %d %d ” , *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4));

o/p : 1 2 3 4 5

Here both statements will print the same values. Why??
Suppose address of arr[0] is 65220. As you know int is 4 bytes(may be other than 4 too, depending on compilers). So address of arr[1] is 65224 and so on.

When we assign array name or first element of array to pointer (ex. ptr=arr or ptr=&arr[0]), value of ptr will be address of first element. So,

ptr = 65220;
*ptr = 1;

ptr+1 = 65224;                 //ptr is of integer type so '+1' increments 4 bytes.
*(ptr+1) = 2;

ptr+2 = 65228;
*(ptr+2) = 3;

And so on ……

Note that array name itself is a pointer to the first element of array. So you can also write statement 1 as below. And it will give same result as above. -> 1 2 3 4 5.

printf (“ %d %d %d %d %d ” , *arr, *(arr+1), *(arr+2), *(arr+3), *(arr+4));

The only difference between Array and Pointer :

Pointer "ptr" is a variable. So that we can use ptr++ to point to next location or next index in array.

In case of array name "arr", it is not a variable. So we can't use arr++. we have to use arr+1, arr+2 and so on.

*Practice programs for pointer to array.
visit : http://letsmakeceasy.blogspot.in/2014/10/tricky-c-programs.html


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

POINTER TO STRING :

Till now to store strings, we have used char array.

char arr[15] = “hello_world!!!”;
printf(“string = %s \n”,arr);

Now we are going to use pointer to access string.

char *ptr = “hello_world!!!”.
printf(“string = %s \n”, ptr);

same output : hello_world!!!

Here the string "hello_world!!!" will be stored inside the data section of our executable. And by using *ptr = "hello world!!!" we are not creating copy of our string but ptr points to the location where our string is been stored.

Many people may have question Why we are not using malloc (dynamic memory allocation) here? 
or why to use malloc if we can directly assign string to pointer (ex. *ptr ="hello") ?

Answer : when we are writing *ptr = "hello", it becomes static allocation of memory for string and it becomes read only. What I am saying is, we can't modify string if needed.

but when we use malloc to store string we can modify it when needed(during execution).

ex.
char *ptr = (char *) malloc(size of string);
strcpy(ptr,"hello");

I think this is enough for pointer to string.

*Practice programs for pointer to string.
visit : http://letsmakeceasy.blogspot.in/2014/10/tricky-c-programs.html


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

POINTER TO STRUCTURE :

I hope you are aware with the concept of structure.
You can define pointer to structure in similar way as you define pointer to any other variable
as follows:
struct list *ptr;

Let's see the program for pointer to structure.

#include <stdio.h>
#include <string.h>

struct list
{
int num;
char name[10];
int mark;
};

void func(struct list *);

void main(void)
{
struct list var1 = {1, "akash", 99};
struct list var2;

var2.num = 2;
strcpy(var2.name,"patel");
var2.mark = 95;

struct list *ptr1 = &var1;
struct list *ptr2 = &var2;

printf("\n Details of student1");
printf("\n Roll Num : %d ", ptr1->num);
printf("\n Name      : %s ", ptr1->name);
printf("\n Marks      : %d \n", ptr1->mark);

printf("\n Details of student2");
printf("\n Roll Num : %d ", ptr2->num);
printf("\n Name     : %s ", ptr2->name);
printf("\n Marks     : %d \n", ptr2->mark);

func(ptr1);    // calling a function and passing details of student1.
                    // to do so, we have to pass only the pointer of variable for student1.
                    // its member will automatically accessible to called function. 
                       // because they are globally defined. 

   //or func(&var1);  both are same .

}

void func(struct list *new_var)
{
printf("\n I am Inside a Function \n");
printf(" Roll Num : %d\n ", new_var->num);
printf(" Name     : %s\n ", new_var->name);
printf(" Marks    : %d\n ", new_var->mark);
}

Explanation : 

Here num, name[10] and mark are members of structure list.
var1 and var2 are variables of structure.
ptr1 and ptr2 are pointers to structure.

Now let's see the difference between variable of structure and pointer to structure.

when we access members of structure using variable of structure we have to use "." operatore.
ex.
var1.num
var1.name
var1.mark

and to access them with pointer to structure we will use "->" . 
ex.
ptr1->num
ptr1->name
ptr1->mark

these are equivalent to,
(*ptr1).num
(*ptr1).name
(*ptr1).mark
At the start of main function I have shown two different ways of assigning value to member of structure.

Then I have declared pointers to structure variables.
ptr1 = &var1;
ptr2 = &var2;

Here ptr1 and ptr2 are pointers to single variable var1 and var2 respectively.

We can also have pointer to array of structure variables.
ex.
struct list var[10];
struct list *ptr;
ptr = &var;

FUNCTION POINTER :

Function pointer is also one of the most important topic in C. To know more about it visit this link.  

http://letsmakeceasy.blogspot.in/2014/10/function-pointer.html


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

At this stage I am going to end this discussion on a magical pointer.

If anyone have query, question or suggestion please write it in the comment box bellow.

Are you a Fresh Programmer?? Join facebook group to be a perfect programmer.

https://www.facebook.com/groups/121611948548929/

To know more on another important topic in c “C PREPROCESSOR

Thanks,
Akash Patel.