Monday, 9 May 2016

Pointers

Most of beginners get fainted when they hear the word pointer. Sometimes it happen with some experienced programmers also. But believe me. Pointers is much easier then we think.

Let us understand the word pointer at first. We try it to understand from the real world example. Pointer means, one who points. Points to whom? Points to anywhere. Like, some lecturer use laser pointer to point on PowerPoint presentations. Yes that is a pointer.

Similarly in programming, one who points to a variable is called pointer.

To understand the concepts of pointers, we will use this analogy through this blog.

There are three most important topics related to pointers.
1. Declaration (Types of pointers)
2. Indirection operator
3. Pointer arithmetic

1. Declaration:
First we see the declaration. In real world, same laser pointer can be used to point at any object on the screen. But in case of C, we need to use different types of pointers. For example, to point int variable, we need to declare the pointer in int type itself. To point float variable, we need to declare the pointer in the float type itself. We will discuss the reason behind it in the pointer arithmetic.

2: Indirection operator:
Suppose screen of PowerPoint presentation is divided in 1"x1" blocks. We to describe an object directly putting a boundary beside a block. This is called direct access.
Now the pointer is pointing on some block. And we have to describe the object being pointed by the pointer. Here we see that, instead of fetching data directly from the block, we check for the block which is being pointed by pointer. We are accessing the block indirectly. This situation is called indirection. And the operator used for this is called indirection operator.

In programming, * is used as indirection operator.
For example:

int a=6;
int *x=&a;
cout<<a<<endl;
cout<<x<<endl;
cout<<*x<<endl;

Output:
6
3202           //can be any value,depending runtime allocation
6

Description:
Value of a is 6
Value of x = address of a = 3202
Value at location pointed by x = value of a = 6

3: Pointer Arithmetic:
I will update it soon. I am sorry for that.