Matrix Multiplication Function

I am having a bit a trouble why when I wanna use heap allocation with pointer my function doesn't work. But it does when I use [][] notation for the array.

Works
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int MAX = 5;
void Multiply(double m1[MAX][MAX], double m2[MAX][MAX])
{
	double mult[10][10] = {};
	for (int row = 0; row < MAX; row++)
	{
		for (int col = 0; col < MAX; col++)
		{
			for (int in = 0; in < MAX; in++)
			{
				mult[row][col] += m1[row][in] * m2[in][col];
			}
			cout << mult[row][col] << "\t";
		}
		cout << "\n";
	}
}


Doesn't Work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Multiply(double* m1, double* m2, int n)
{
	double* mult = new double[n*n];
	for (int row = 0; row < n; row++)
	{
		for (int col = 0; col < n; col++)
		{
			for (int in = 0; in < n; in++)
			{				
				mult[row* n + col] = m1[row* n + in] * m2[in * n + col];
				mult[row* n + col] = mult[row* n + col] + mult[row* n + col];
			}	
			cout << mult[row* n + col] << "\t";
		}
		cout << "\n";
	}
}


Output for M1 = [ 1 2 ] [ 3 4 ] M2 = [ 5 6 ] [ 7 8 ]

M1* M2 = [ 28 32 ] [ 56 64 ](INCORRECT)
Last edited on
Topic archived. No new replies allowed.