45. Passing 2-D Array to a Function by using pointer

There are two ways in which er can pass a 2-D array to a function by using pointer. These are illustrated in the following program.

/*Two ways of accessing a 2-D array*/
#include<alloc.h>
void main()
{
int a [3][4]={
               1,2,3,4,
               5,6,7,8,
               9,0,1,6
             };
clrscr();
display(a,3,4);
show(a,3,4);
}

display(int *q,int row, int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",*(q+i*col+j));
printf("\n");
}
printf("\n");
}

show(int (*q)[4],int row, int clo)
{
int i,j;
int *p;

for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
printf("\n");
}

And here is the output...

1234
5678
9016

1234
5678
9016

In the display() finction we have collected the base address of the 2-D array being passed to it in an ordinary int pointer. Thenthrough the two for loops using the ex[ression *(q+i*col+j) we have reached the appropriate element in the array. Suppose i is equal to 2 and j is equal to 3, then we wish to reach the element give this element or not. The exprewssion *(q+i*col+j) becomes *(4001+2*4+3). This turns out to be *(4001+11). Since 4001 is address of an integer, *(4001+11) turns out to be *(4023). Value at this address is +. This is indeed same as a[2][3]. A more general formula for accessing each array element would be:

*(base address + row *no of columns +column no)

In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration
int (*q)[4];

To begin with, q hods the base address of the xeroth 1-D array, i.e 4001. This address is then assigned to p, an int pointer, and then using this pointer all elements of the xeroth 1-D array are accessed. Next thime through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D arry. This is because, q is a pointer to zeroth 1-D array and adding 1 to it would given us the address of the next 1-D array. This address is once again assigned to p, and using it all elements of the next 1-D arraY are accessed. 

Arnob

2 comments:

free counters