Reputation: 33
The code is supposed to add together 2 matrices and output a 3rd one tht is the result of the first two. I think this should work, but whenever I try to run it I get an error!
It looks like my post is mostly code but I think I explained enough.
#include<iostream>
using namespace std;
//Study........
int main()
{
int matrixC[10][10];
int l,m,z,n;
cout<< "Please input the dimensions of the first matrix"<< endl;//MatrixA
cin>> l;
cin>> m;
int **matrixA = new int*[l];
for(int i = 0; i < l; i++)
{
matrixA[i] = new int[m];
}
for(int i=0; i < l; i++){
delete [] matrixA[i];
}
delete [] matrixA;
cout<< "Please input the dimensions of the second matrix"<< endl;//MatrixA
cin>> z;
cin>> n;
int **matrixB = new int*[l];
for(int i = 0; i < l; i++)
{
matrixB[i] = new int[m];
}
for(int i=0; i < l; i++){
delete [] matrixB[i];
}
delete [] matrixB;
/*cout<<"enter the dimension of the first matrix"<<endl;
cin>>l>>m;
cout<<"enter the dimension of the second matrix"<<endl;
cin>>z>>n;
if(m!=z||z!=m){
cout<<"error in the multiplication enter new dimensions"<<endl;
cout<<"enter the dimension of the first matrix"<<endl;
cin>>l>>m;
cout<<"enter the dimension of the second matrix"<<endl;
cin>>z>>n;
}*/
cout<<"enter the first matrix"<<endl;
for(int i=0;i<l;i++){
for(int j=0;j<m;j++){
cin>>matrixA[i][j];
}
}
cout<<"enter the second matrix"<<endl;
for(int i=0;i<z;i++){
for(int j=0;j<n;j++){
cin>>matrixB[i][j];
}
}
for(int i=0;i<l;i++){
for(int j=0;j<n;j++){
matrixC[i][j]=0;
for(int k=0;k<m;k++){
matrixC[i][j]=matrixC[i][j]+(matrixA[i][k] * matrixB[k][j]);
}
}
cout<<"your matrix is"<<endl;
for(int i=0;i<l;i++){
for(int j=0;j<n;j++){
cout<<matrixC[i][j]<<" ";
}
cout<<endl;
}
}
//system("pause");
return 0;
}
Upvotes: 0
Views: 147
Reputation: 451
There are two problems:
a) You delete Matrix A & B after allocating
b) You never allocate Matrix C
Upvotes: 0
Reputation: 991
No wonder… You delete[]
both matrixA
and matrixB
and then the code like cin>>matrixA[i][j]
causes the crash because of invalid memory writes.
Upvotes: 5