代码应该将2个矩阵相加并输出第3个,这是前两个的结果。我认为这应该有效,但每当我尝试运行它时,我都会收到错误!
看起来我的帖子主要是代码,但我想我解释得不够。
#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;
}
答案 0 :(得分:5)
难怪...... delete[]
matrixA
和matrixB
cin>>matrixA[i][j]
然后像{{1}}这样的代码导致崩溃,因为内存写入无效。
答案 1 :(得分:0)
有两个问题:
a)您删除Matrix A&amp; B分配后
b)你永远不会分配Matrix C