POINTERS
TO ARRAYS:
Whenever
an array is declared, the compiler allocates sufficient amount of storage
locations to store all the elements
of the array.
Eg., int
a[5]={10,11,12,13,14};
|
The
address of first element of an array is called base address and this is stored
in corresponding variable name.
i.e., a=&a[0]=5000.
The
address of remaining elements can be found by simply adding the index value to
the array name.
i.e., a+1=&a[1]=5002
a+2=&a[2]=5004
a+3=&a[3]=5006
a+4=&a[4]=5008
The address of an array element can
be calculate directly by using the formula:
address=base address+(index*scale factor)
Eg.,
address
of a[3]=5000+3*2=5006.
Whenever
pointer to an array is declared, the pointer variable has to be initialized to
the base address of the array.
Eg.,
int
a[5],*pt;
Initialization can be done as:
pt=a;
or pt=&a[0];
The
address of remaining elements can be found by adding the index value to the
pointer variable.
i.e.,pt+1=&a[1]
pt+2=&a[2]
pt+3=&a[3]
pt+4=&a[4]
The
values of array elements can be accessed through *(pt+i). Where, ‘i’ indicates
the index of the array element. i.e., value of elements at base address =*pt;
*(pt+1)=a[1]
*(pt+2)=a[2]
*(pt+3)=a[3]
*(pt+4)=a[4]
NOTE:- *pt+i is different from
*(pt+i). *pt+i adds ‘i’ to the value at address pt, whereas *(pt+i) indicates
the value at address (pt+i).
Ø A
Program to print elements of an array using pointer to array.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],*pt,i,n;
pt=a;
printf(“enter size of
the array”);
scanf(“%d”,&n);
prnitf(“enter
elements”);
for(i=0;i<n;i++)
scanf(“%d”,pt+i);
printf(“the elements
are”);
for(i=0;i<n;i++)
scanf(“%”,*(pt+i));
getch( ); }
Pointers
to 2D arrays:
A pointer to a 2D array can be
declared similar to a pointer to 1D array.
Eg.,
int
a[2][3]={1,2,3,4,5,6};
The base address of the array has to
be initialized to the pointer variable such as:
pt=a or
pt=&a[0][0];
The address of an element can be
calculated by the following formula:
Address=base address+column size*i+j
Where ‘i’ indicates the row position
and j indicates column position respectively.
Eg.,
Address
of a[1][1]=5000+3*1+1
=5000+(4*2)
=5008.
Ø A
Program to read and print elements of 2D array using pointers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10],*pt,i,j,m,n;
pt=a;
printf(“enter rows and column size of the
array”);
scanf(“%d%d”,&m,&n);
printf(“enter elements”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,(pt+n*i+j));
printf(“the elements are”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d\t”,*(pt+n*i+j));
getch( );
}
No comments:
Post a Comment