0

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++ 编译器给出错误“分段错误”我尝试了调试方法(在此站点上找到)但未能消除错误!

有什么帮助吗?

4

2 回答 2

2

这一行是错误的:

matrix* tMat = (matrix*)malloc(sizeof(matrix));

我不完全确定你期望它做什么,但它可能不会那样做......事实上,它根本没有做太多事情,除了为结构创建一个足够大的内存块matrix. 它充满了一些随机垃圾(可能是也可能不是零)。

然后你继续使用它:

                tMat->mat[j][i] += matA->mat[j][m] * matB->mat[m][i];

这很可能意味着您正在访问 NULL 或一些无效的随机垃圾地址。然后返回指向它的指针,这里没有释放它:

matrix* matC = MultiplyMat(&matA,&matB);
PrintMatrix(matC);

return 0;

你可能想要这样的东西:

matrix* tMat = new matrix(matB->col, matA->row);

但是你最好创建一个matrix operator*(const matrix& a, const matrix& b),所以你根本不返回一个指针。开销会很小。

于 2013-10-01T20:04:54.527 回答
0

您的矩阵实际上有一个构造函数,但在使用分配内存时不会调用它malloc()。你显然想使用

matrix* tMat = new matrix(m, n);

有合适的论据mn。好吧,实际上,您宁愿使用

std::unique_ptr<matrix> tMat(new matrix(m, n));

...但这与您克服分段错误后将遇到的下一个问题有关:您还需要清理资源。不过,这也不是你真正想要的,因为你真的想要这样的东西:

matrix MultiplyMat(matrix const& a, matrix const& b) {
     // ...
     matrix result(m, n);
     // ...
     return result;
}
于 2013-10-01T20:09:15.967 回答