Matrix Multiplication

Hello all I am having trouble trying to multiply 2 matrix together. I keep getting a segmentation fault core dumped error and I am not sure why. The only thing I can think of is I am using the wrong number for n, I think it should be the number of numbers in the matrix but I am not sure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 #include <iostream>
using namespace std;
//const int SIZE = 100;
//typedef double Matrix[SIZE][SIZE];

void multiply(double a[5][2], double b[5][2], double c[5][2], int n)
{
   int i, j, k;
   for (i = 0; i < n; i++)
      for (j = 0; j < n; j++)
      {
         c[i][j] = 0;
         for (k = 0; k < n; k++)
            c[i][j] += a[i][k] * b[k][j];
      }
}


int main()
{

double matrix1[5][2]={{1,2},
                      {4,5},
                      {7,8},
                      {2,4},
                      {3,6}};


double matrix2[5][2]={ {10,11},
                       {13,14},
                       {16,17},
                       {19,20},
                       {23,25}};


double matrix3[5][2] ={{0,0},
                       {0,0},
                       {0,0},
                       {0,0},
                       {0,0}};


 multiply(matrix1,matrix2,matrix3,10);

cout <<matrix3[0][0]<<endl;
}
closed account (o1vk4iN6)
You can't multiply a 5x2 matrix by another 5x2 matrix. You have to respect the bounds of the arrays you define:

multiply(...,10);

The 10 you specify there is being used for indices of [5][2] which is out of bounds in both cases.

http://www.cplusplus.com/doc/tutorial/arrays/
Hi xerzi thank you for the help. We havn't gone over matrix yet so I'm a little confused. I need n to be 10 so would that mean I need to multiply a 5x2 by a 2x5 and c would be a 5x5?
Topic archived. No new replies allowed.