AoA,这是两个矩阵相乘的代码,它在 3x3 矩阵下运行良好,但在超出 3x3 的行或列时会出错,就像在 3x4 和 4x3 上一样,它会给出错误“分段错误”
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct matrix
{
int** mat;
int row;
int col;
matrix(int m,int n)
{
row = m;
col = n;
mat = new int*[row];
for( int i=0;i<row;i++ )
{
mat[i] = new int[col];
for( int k=0;k<col;k++ )
{
mat[i][k] = 0;
}
}
}
};
matrix* MultiplyMat(matrix* matA,matrix* matB)
{
matrix* tMat = new matrix(matA->row,matB->col);
if(matA->row == matB->col)
{
for( int i=0; i<matA->row; i++ )
{
for( int j=0;j<matB->col;j++ )
{
for( int m=0;m<matB->col;m++ )
{
tMat->mat[j][i] += matA->mat[j][m] * matB->mat[m][i];
}
}
}
}
return tMat;
}
void PrintMatrix(matrix* tMat)
{
cout<<"Print: Matrix\n\n";
for( int i=0;tMat->row;i++ )
{
for( int j=0;j<tMat->col;j++ )
{
cout<<" "<<tMat->mat[i][j];
}
cout<<"\n";
}
}
int main()
{
matrix matB(3,4);
matrix matA(4,3);
matA.mat[0][0] = 2;
matA.mat[0][1] = 1;
matA.mat[0][2] = 4;
matA.mat[1][0] = 6;
matA.mat[1][1] = 5;
matA.mat[1][2] = 9;
matA.mat[2][0] = 8;
matA.mat[2][1] = 7;
matA.mat[2][2] = 11;
matA.mat[3][0] = 5;
matA.mat[3][1] = 5;
matA.mat[3][2] = 9;
matB.mat[0][0] = 2;
matB.mat[0][1] = 1;
matB.mat[0][2] = 4;
matB.mat[0][3] = 3;
matB.mat[1][0] = 6;
matB.mat[1][1] = 5;
matB.mat[1][2] = 9;
matB.mat[1][3] = 12;
matB.mat[2][0] = 8;
matB.mat[2][1] = 7;
matB.mat[2][2] = 11;
matB.mat[2][3] = 13;
matrix* matC = MultiplyMat(&matA,&matB);
PrintMatrix(matC);
return 0;
}
我只是想多玩两个矩阵,g++ 编译器给出错误“分段错误”我尝试了调试方法(在此站点上找到)但未能消除错误!
有什么帮助吗?