简体   繁体   English

每当我运行C ++中的乘法矩阵代码时,它都会不断崩溃。 无法找出原因

[英]Multiplication Matrix Code in C++ keeps crashing whenever I run it. Cannot figure out why

The code is supposed to add together 2 matrices and output a 3rd one tht is the result of the first two. 该代码应该将2个矩阵相加并输出第三个矩阵,这是前两个矩阵的结果。 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;
}

难怪……您同时delete[]matrixAmatrixB delete[] ,然后像cin>>matrixA[i][j]类的代码由于无效的内存写入而导致崩溃。

There are two problems: 有两个问题:

a) You delete Matrix A & B after allocating a)您在分配后删除矩阵A和B

b) You never allocate Matrix C b)您永远不会分配矩阵C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM