pass and return array in a function
Mar 22, 2011 at 1:36pm UTC
I am having two matrices, A, B. I would like to pass A and B into a function, which calculate C=A-B, and return it.
How to write this function using pointer passing. I tried to define it as
1 2 3
int m1[100][100];
int m2[100][100];
m3 = subtractM(m1,m2, 100);
Should the function be defined as
int **p = multiM(int **x1, int **x2, dim)
Mar 22, 2011 at 2:16pm UTC
Last edited on Mar 22, 2011 at 2:16pm UTC
Mar 22, 2011 at 2:33pm UTC
Some template magic could also be useful here...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
template <class T, int Rows, int Cols>
void matrix_sub(T const (&m1)[Rows][Cols],
T const (&m2)[Rows][Cols],
T (&m3)[Rows][Cols])
{
//m3=m1-m2
}
int main()
{
double md23[2][3];
int mi23[2][3];
int mi34[3][4];
matrix_sub(md23,md23,md23); //ok
matrix_sub(md23,md23,mi23); //problem
matrix_sub(mi23,mi34,mi23); //problem
return 0;
}
Passing (const) references to the arrays allows the compiler to deduce the type,
which saves you some typing ->
matrix_sub<double , 2, 3> (...)
Topic archived. No new replies allowed.