Friday, August 27, 2010

Array and pointers in C programming language


When an array is declared in C language, compiler allocates a base address and sufficient amount of storage to hold the elements. The base address is the location of the first element (index 0) .The compiler also defines the array name as a constant pointer to the first element. Suppose we declare an array as follows:
                                   int arr [4] = [1,2,3,4};

The array name arr is defined as a pointer pointing to the first element arr [0] and therefore the value of arr is 1000(say),the location where arr [0] is stored. arr = &arr [0] = 1000

The address of the second element can be written as either &arr [1] or arr+1.Here the expression arr+1 represents an address rather than an arithmetic expression. Now if we declare ptr as a pointer variable and want to point the array arr, then the statement looks like: ptr = arr;This is equivalent to ptr = &arr [0];
We can access every value of arr using ptr++ to move from one element to another.*(ptr+2) gives the value of arr [2]. The pointer accessing method is much faster than array indexing.

Here is a C Program to demonstrate the above feature


#include< stdio.h>
void main ()
{
int *ptr, sum, i;
int arr [4]={1,2,3,4};
clrscr ();
i=0;
sum=0;
ptr=arr;
printf ("Element   Value     Address\n");
while (i< 4)
{
 printf ("arr [%d]    %d         %u\n", i, *ptr, ptr);
 sum=sum+*ptr++;
/*note ‘postfix’ operator.*/
 i++;
  }
 printf ("\nSum is:-%d", sum);
 getch ();
 }

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner