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.


5 comments:

  1. Please Explain in detail topic pointer to string
    I didn't understand it.

    ReplyDelete
  2. hello, Dhruvin.
    i have added some new stuff for pointer to string. plz refer it again.

    ReplyDelete
  3. Thank you so much
    All my doubts are clear!
    Can you please post on
    Pointer to Structure

    ReplyDelete
  4. pointer to structure is ready now.

    ReplyDelete
  5. hii
    Can you please post on only topic covered
    Structure and Union
    I really appretiate your work!!
    Please Keep it up!!!

    ReplyDelete