I’m new to C++ and I’m trying to write a program that multiplies two arrays using double pointers. My code so far is:
#include <iostream>
using namespace std;
//multiplies two matrices A(mxl) and B(lxn) to produce C(mxn)
int m,l,n;
int **A, **B, **C;
void main(void)
{
…user inputs m,l,n and allocates memory like this.
int i, j;
//creates a new mxl array
A= (int**) new int*[m];
for(i=0;i<m;i++)
{
A[i]=new int[l];
}
//creates a lxn array
B = (int**) new int*[l];
for(i=0;i<l;i++)
{
B[i]=new int[n];
}
//creates a mxn array
C = (int**) new int*[m];
for(i=0;i<n;i++)
{
C[i]=new int[n];
}
int sum = 0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(int k=0;k<l;k++)
{
sum =+ A[i][k]*B[k][j];
}
}
//cout<sum<<"\t";
so far everything works fine. If I change this to just cout ‘sum’ then it returns all the correct elements of the array in the right order; it’s when I try to put this value into the array that it returns an error message.
C[i][j]=sum;
}
}
I’m sure there’s a much better way to multiply matrices together but I’m much more interested in knowing why this particular piece of code doesn’t work; it looks very simple and I can’t see where the error is coming from.
In your update you added this code:
The loop condition is incorrect. Instead of
i<nyou needi<m.Your multiplication loop looks like this:
The assignment
C[i][j]is in the wrong block–the[j]array access is out-of-bounds.It should be like this:
Note that I have initialised
sumto 0 every time a newjloop is started. That corrects another error in your code.It would be a lot better if you declared the variables with the tightest scope possible. Like this:
Had you done that the compiler would have rejected your original placement of the assignment to
C[i][j].Your
mainfunction should be declared like this:and you should return a value from your
main().