# Thread: 2D array passing to function

1. ## 2D array passing to function

well here's the call

rec_function(matrix_a, matrix_b, multiply, user);

/* that's 3 already initialized matrix's, plus the size (square) */

/*and here's the function*/

int rec_function(int **a, int **b, int **c, int n)
{
int i,j;

if(n==1) //base case (works fine)
{
**c=(**a)*(**b);
return **c;
}

if(n==2)
{
**c=(**a)*(**b)+(**(a+1))*(**(b+2));
**(c+1)=(**a)*(**(b+1))+(**(a+1))*(**(b+3));
**(c+2)=(**(a+2))*(**b)+(**(a+3))*(**(b+2));
**(c+3)=(**(a+2))*(**(b+1))+(**(a+3))*(**(b+3));
return **c;
}

}

Man that looks like hell, anyways, I was under the assumption that by using **(b+1) or **(a+3) or whatever, that it would move the pointer to the right in my array, but of course it moves it down.

eg
| 4 7 |
| 6 8 | I want 7, but get 6..

Is there an easier way of doing this (I think I tried most), or am I missing something as I've never dealt with this type of issue before. I'll keep plugging away at it, but hopefully someone's has so help for me.

2. There is an easier way to pass 2D arrays, take a look at this example. Perhaps it's not the most elegant way, but it some clearer than your way.

Code:
```#include <stdio.h>
#include <string.h>

void fill (int array [3][4])
{
int x,y;

for (x = 0; x < 3; x++)
{
for (y = 0; y < 4; y++)
{
array [x][y] = x;
}
}
}

void print (int array [3][4])
{
int x,y;

for (x = 0; x < 3; x++)
{
for (y = 0; y < 4; y++)
{
printf ("i [%d,%d] = %d\n", x, y, array [x][y]);
}
}
}

int main ()
{
int i [3][4];
int x,y;

fill (i);
print (i);

return 0;
}```

3. Code:
```void MatrixMultiply(double mat1[4][4],double mat2[4][4],double result[4][4])
{

for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
{
matrix[i][j]=0;
for (int k=0;k<4;k++)
{
matrix[i][j]+=matrix[i][k]*matrix[k][j];
}
}
}
}```
This will concatenate two 4x4 matrices and is very useful for 3D graphics. This can be sped up a bit by unrolling the third loop since most of the time is spent there.

4. Yikes!!!

Should be this, sorry.

Code:
```void MatrixMultiply(double mat1[4][4],double mat2[4][4],double result[4][4])
{

for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
{
result[i][j]=0;
for (int k=0;k<4;k++)
{
result[i][j]+=mat1[i][k]*mat2[k][j];
}
}
}
}```

5. thanks for the help guys, I actually figured it out before coming back here. I also should have said that I was to do it recursively only, hence making a little more sence to my above madness. I did end up passing it like yours above though using[][] instead of **

~mike~

6. No, it still does not make sense the way you did it, even for a recursive implentation - which is dumb, by the way, since the iterative approach gets the job done nicely.