矩阵乘法中的指针不起作用

时间:2017-11-17 06:15:59

标签: c++

class mm
{
    public :
    static int** multiPlyMatrix(int** matrix1, int** matrix2,int r1,int c1,int r2,int c2) {
    int** multiplication;

    if (c1==r2)
    {
    multiplication=new int*[r1];
    for (int row = 0; row < r1; row++)
    {
        multiplication[row]=new int[c2];

        for (int colIndex = 0; colIndex <c2; colIndex++)
        {
            for (int col = 0; col <r2; col++)
            {
                multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];
            }
        }
    }
    }else
    {
           cout<<"Multiplication Not Possible"<<endl;
    }
        return multiplication;
    }

    static void deleteMemory(int** array,int rows)
    {
        if(array)
        {
            for(int i=0;i<rows;i++)
            {
                if(array[i])
                {
                    delete[]array[i];
                }
            }
            delete[] array;
        }
    }
};
void main()
{
    mm obj;
    int r,c;
    char ch;
    int rows,cols,rows2,cols2;
    int** matrix1;
    int** matrix2;
    int** result;
    do{
     rows=0,cols=0,rows2=0,cols2=0;
    clrscr();
    cout<<"Enter number of rows:";
    cin>>rows;
    cout<<"Enter number of columns:";
    cin>>cols;
    matrix1=new int* [rows];
    cout<<"Enter Elements in Matrix 1:"<<endl;
    for ( r = 0; r < rows; r++)
    {
        matrix1[r]=new int[cols];
        for ( c = 0; c < cols; c++)
        {
         cin>>matrix1[r][c];
        }
    }

    cout<<"Enter number of rows:";
    cin>>rows2;
    cout<<"Enter number of columns:";
    cin>>cols2;
    matrix2=new int* [rows2];
    cout<<"Enter Elements in matrix2:"<<endl;
    for ( r = 0; r < rows2; r++)
    {
        matrix2[r]=new int[cols2];
        for ( c = 0; c < cols2; c++)
        {
        cin>>matrix2[r][c];
        }
    }
    result=obj.multiPlyMatrix(matrix1, matrix2,rows,cols,rows2,cols2);

    cout<<"Multiplication of matrix:"<<endl;

    for ( r = 0; r < rows; r++)
    {
        cout<<"|";
        for ( c = 0; c < cols2; c++)
        {
         cout<<result[r][c] << " ";
        }
        cout<<"|"<<endl;
    }

    obj.deleteMemory(matrix1,rows);
    obj.deleteMemory(matrix2,rows2);
    obj.deleteMemory(result,rows);
    cout<<"\nWanna Enter Again?(y/n):";
    cin>>ch;
    }while(ch=='y'||ch=='Y');
}

所以,这就是完整的代码,程序在第一次运行时效果很好,但是当我第二次运行它时它会将垃圾值作为输出,当我退出IDE并再次打开它时它将第一次运行很好然后它会再次运行垃圾值, 我做错了什么?

我认为删除方法存在一些问题,我使用turbo c ++作为IDE和gcc编译器

1 个答案:

答案 0 :(得分:0)

您期望multiplication[row][colIndex]第一次使用它的代码行被击中? (为了非常清楚,你需要在阅读之前对其进行初始化。)

这在调试器中很明显。学习cgdb(在Cygwin或WSL上)或尝试Oracle Netbeans C++下载包。 VS 2017社区版也可以使用gcc和cmake(使用直接Makefile时可以少一些)。

multiplication[row]=new int[c2];

for (int colIndex = 0; colIndex <c2; colIndex++)
{
    for (int col = 0; col <r2; col++)
    {
        multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];