Thursday, 21 February 2013

Declaring, Initializing and Accessing Pointer Variable in C

In, this tutorial you will learn how to declare, initialize and access pointer variables. The tutorial is divided into four parts.

Table of content:




Understanding Pointers

Before getting into it, you need to understand why pointers are used. So, here is an explanation for it. 
"Each value that you store in variable has a unique address." Let's understand this with an example



 As you can see in the above image, we have initialized integer type variable and stored a value(10) in it. In the second line, printf prints (a+5) ie. 15. Now the core part of this example. Here, we get two values 10 and 15. Now, just think, where would be these values stored in our computer's memory....????
The answer is "address". Each value that we store or that we get as an output is stored at a unique address. See below given image.

Here, pointers come in. Pointers stores the address of the particular value and also indirectly the value.
Now, what if you want to know the address of the particular value?
Check out these example:


OUTPUT
 Here, we have used ' & '  ie. ampersand, for getting the address the value ' A ' stored in variable '  a '. And for printing the address, ' %u ' is used. Because, addresses are unsigned integers. 
Below, are some illegal use of ' & ' operator:
1)  &125 (address of constants not possible)
2) int x[3];
    &x (cannot point address to array names, will learn late)
3) &(x+y) (cannot point to expressions)

Declaring Pointer Variables

Syntax to declare a pointer variable:

data_type *pointer_name;


When you declare a pointer with above syntax, you tell the compiler three things about the variable(pointer_name) :
1)  ' * ' shows that pointer_name is a pointer variable.
2)  pointer_name needs a memory allocation ( ie. address).
3)  pointer_name points to a variable of type data_type. 

Some declaration examples:
 ->  int *p
->  float *ptr


Initialization of Pointer Variables

Now, you have declared the pointer variable, and its time to Initialize (ie. store some value). Look at below given examples:

OUTPUT: