Arrays using pointers

Arrays using pointers: The pointer is very useful in the array. If we want to store the address of the array in a variable then it gives its base address and through which we can easily access all of other elements of the array. Accessing the array with the pointers is much faster than the array indexing.

e.g:      int  a[4]={2,11,5,7};

Let suppose array is starting from 2000 then array will be stored as:

Sequence         value   address

a[0]      =          2          2000

a[1]      =          11        2002

a[2]      =          5          2004

a[3]      =          7          2006

Now if we want the array points through a pointer variable then it will be as:

p=&a[0];

or

p=a;

Both are same and p is now containing the base address or can say starting address of the array. Now we can easily access the rest of the elements by increment the pointer.

If p is a pointer variable pointing to base address of the array then we can increment it like:

p++; by this it is now pointing to next address which is 2002.

Program:

PROGRAM TO ADD ALL THE ELEMENTS OF ARRAY USING POINTERS

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10],n,i,sum=0;

int *p;

clrscr();

printf(“Enter the size of array: “);

scanf(“%d”,&n);

printf(“Enter %d elements in the array:\n”,n);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

p=&a[0];

printf(“Entered elements are:\n”);

for(i=0;i<n;i++)

{

printf(“%5d”,*p);

sum=sum+(*p);

p++;

}

printf(“\nSum of elements of array is: %d”,sum);

getch();

}

Posted in C

Leave a Reply

Your email address will not be published. Required fields are marked *