Sunday, September 2, 2012

Concept of Pointer

In last chapter ( what is pointer ) , we learn what is the basic of pointer. Now we are learning what is the concept of pointer and how to using it.

In last chapter we declare a variable
int n = 10 ;
and create a memory map, Now we learn how to do this.

Now we print the address of variable through following program:

#include<stdio.h>
int main()
{
  int n = 10;
  printf("\nAddress of n =%u", &n);
  printf("\nValue of n =%d", n);
  getch();
  return 0;
}

The output of above program:

Address of n = 65220
Value of n = 10

Useful tips i.e. explanations of above programs:
  • Look at the first printf() statement carefully, it used & ( address of operator ). So & return the address of memory location. In our case, the expression  &n return the address of variable n.
  •  %u is used for printing the unsigned integer.
Now, observe carefully the output of the following program:

#include<stdio.h>
int main()
{
  int n = 10;
  printf("\nAddress of n =%u", &n);
  printf("\nValue of n =%d", n);
  printf("\nValue of n =%d", *(&n));
  getch();
  return 0;
}

The output of above program:


Address of n = 65220
Value of n = 10
Value of n = 10

here you can notice that the value of *(&n) is same as printing the value of n.

The expression &n gives the address of the variable n. This address can be collected in a variable, by saying:

int p = &n;

but here 1 problem, p is simple variable so we can't use of variable p.
What is solution?
So here comes the concept of pointer. Now we declare the integer variable p as integer pointer variable:

int *p;
This declaration tells the compiler that p will be used to store the address of an integer value i.e. p points to an integer.

int *p;

Now let's understand the meaning of *. It stand for value at address  operator. It return the value at stored at particular address.
The "value at address" operator is also known "indirection operator".

Thus, 
int *p; would mean, the value at the address contained in p is an int.

let's check out what you grab:
Q. What will be output of following program?
  
     #include<stdio.h>
     int main()
     {
        int n = 10;
        printf("\nOutput of n =%d", n);
        printf("\nOutput of *n =%d", *n);
       getch();
       return 0;
     }

Ans.

Output of n = 10
Output of *n = error ( invalid indirection)

Can you understand why second printf() statement generate error? if yes then congratulation... And if you can't figure out then also don't worry because our next chapter is pointer practice session, in this you grab all about pointer.

The reason second printf() statement is generating error because, "value at address ( * )" is used only pointer variable/directly address i.e. "value at address" does not work with simple variable.
In our case n is simple variable and so compiler generate error.


Related programs:


  1. What is Pointer ?
  2. Pointer basic example
  3. Pointer extend example

No comments:

Post a Comment