pass and return array in a function

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)
Sorry, I don't see any function definition, but yeah, that's how you do it with 2D arrays, try to search this site for more examples e.g: http://www.cplusplus.com/forum/articles/7459/ (using 2D vectors and pointers)
Last edited on
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.