Multi-dimensional array can also be
represented with an equivalent pointer notation as in single dimensional array.
A two dimensional array is actually a collection of one dimensional arrays.
Therefore we can define a two dimensional array as a pointer to a group of contiguous
one-dimensional arrays. Its general syntax is as
Data_type (*ptr_variable)[expression2];
Instead of
Data_type
array[expression1][expression2];
Example:
Suppose x is a two dimensional integer
array having 4 rows and 5 columns. We can declare x as
int (*x)[5];
rather than
int x[4][5];
Here, in first declaration,
x is defined to be a pointer to a group of contiguous one dimensional 5-element
integer arrays. The x points to the first 5-element array, which is actually
first row of the two dimensional array. Similarly, x+1 points to the second
5-element array, which is the second row of the two dimensional array. It is
illustrated as
An example:
void main()
{
int p[2][3]={ {1,2,3},
{4,5,6}
};
clrscr();
printf("p=%u\tp+1=%u",p,p+1);
printf("\n*p=%u\t*(p+1)=%u",*p,*(p+1));
printf("\n*(p+0)+1=%u\t*(p+1)+1=%u",*(p+0)+1,*(p+1)+1);
printf("\n*(*(p+0)+1)=%u\t*(*(p+1)+1)=%u",*(*(p+0)+1),*(*(p+1)+1));
getch();
}
Output:
p=65514 p+1=65520
*p=65514 *(p+1)=65520
*(p+0)+1=65516 *(p+1)+1=65522
*(*(p+0)+1)=2 *(*(p+1)+1)=5
It can be illustrated as
Example:
Write a program to add two 2*3 matrixes
using pointer.
void main()
{
int (*a)[3],(*b)[3],*(sum)[3],i,j;
clrscr();
printf("Enter first matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",*(a+i)+j);
printf("Enter second Matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",*(b+i)+j);
printf("\nThe sum matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
|
*(*(sum+i)+j)= *(*(a+i)+j)+ *(*(b+i)+j);
printf("\t%d",*(*(sum+i)+j));
}
printf("\n");
}
getch();
}
Comments
Post a Comment