0

AoA、これは 2 つの行列の乗算のコードです。3x3 行列では正常に動作しますが、3x4 や 4x3 のように 3x3 の行または列を超えるとエラーが発生し、「セグメンテーション違反」というエラーが発生します。

#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;
}

2 つの行列をマルチプレイしようとしていますが、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 に答える