## How to pass a multi-dimensional array to a function?

When we pass an array to a function, what really gets passed is a pointer to the array’s base address. We know that when we declare a function that seems to accept an array as a parameter, the compiler quietly compiles the function as if that parameter were a pointer, since a pointer is what it will actually receive. What about multidimensional arrays? What kind of pointer is passed down to the function?

When we  pass a multi-dimensional array, since the first element of a multidimensional array is another array, what gets passed to the function is a pointer to an array. If you want to declare the function func in a way that explicitly shows the type which it receives, the declaration would be

 Source code
```func(int (*a)[7])
{
...
}```

The declaration int (*a)[7] says that a is a pointer to an array of 7 ints. Lets take an example of adding two matrix.

 Source code
```#include<stdio.h>
#define R 10
#define C 10

void showmat(int (*a)[],int,int);
main()
{
int m1[R][C],m2[R][C],m3[R][C],r,c,i,j;

printf("\nEnter no. of rows and columns you want to use");
scanf("%d %d",&r,&c);
printf("\nEnter data for matrix1");
printf("\nEnter data for matrix2");
printf("\nMatrix - 1");
showmat(m1,r,c);
printf("\nMatrix - 2");
showmat(m2,r,c);
printf("\nMatrix - 3 = Matrix -1 + Matrix -2");
showmat(m3,r,c);
return 0;
}
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",*(a+i)+j);
}
}
}
void showmat(int (*a)[C],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",*(*(a+i)+j));

}
}

}
void addmat(int (*x)[C],int (*y)[C],int (*z)[C],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
*(*(z+i)+j)=*(*(x+i)+j)+*(*(y+i)+j);

}
}
}```

This entry was posted in Placements. Bookmark the permalink.