Monday, August 23, 2010

Pointers in C Language

What is pointer


Pointer is the flavor of C Language. It’s a special type of variable that can hold the address of same type of variable. So we can say that variables deals with value while pointers deals with address in C Language.

Consider the following declaration:-
int i =50;
This declaration tells the C compiler to-
Reserve space in memory to store an integer value
Associate the name i  with the memory location
store the value 5 at this location

This feature can be demonstrate with the help of a chart
 Location Name     i
 Value                    50
Address                1000

In C Language, &is called address operator while * is called value at address  or indirection operator.

C program to illustrate the use of pointer

#include< stdio.h >
 void main()
 {
  int i=5;
  printf("\nValue stored is=%d",i);
  printf("\nAddress of the location is=%u",&i);
  printf("\nValue stored is=%d",*(&i));
  }


From the above program it is clear that &i returns the address of i.So, this address can be stored in a variable and address of a variable can be stored in pointer.

The above C  program on pointeris modified as follows:-

#include< stdio.h >
 void main()
 {
  int i=5;
  int *j;
  j=&i;
  printf("\nvalue stored in the pointer(address of the variable'i')is=%u",j);
  printf("\nAddress of the location (through address operator)is=%u",&i);
  printf("\nValue stored (displayed through pointer)is=%d",*j);
  printf("\nValue stored (displayed through variable)is=%d",i);
  printf("\nAddress of the pointer is=%u",&j);
  }




No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner