#include <iostream>
#include <malloc.h>
using namespace std;
int main()
{
int r,c,r2,c2;
cout << "Enter the number of rows:- \n";
cin >> r;
cout << "\n" <<"Enter the number of columns: \n";
cin >> c;
int **mat;
int **mat2;
mat=(int**)malloc(sizeof(int)*r); // allocating memory to a row
for (int i=0;i<r;i++)
{
*(mat+i)=(int*)malloc(sizeof(int)*c); /* allocating memory to
columns in rows ( double pointers ) */
}
cout << "\n\n" << "Please enter the 1st matrix of order:- " << r << 'x'
<< c<< endl;
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cin >> *(*(mat+i)+j);
cout << endl;
}
}
cout << "Enter the number of rows(2nd):- \n";
cin >> r2;
cout << "\n" <<"Enter the number of columns(2nd): \n";
cin >> c2;
mat2=(int**)malloc(sizeof(int)*r2);
for (int i=0;i<r2;i++)
{
*(mat2+i)=(int*)malloc(sizeof(int)*c2);
}
cout << "\n\n" << "Please enter the 2nd matrix of order:- " << r2 << 'x'
<< c2 <<endl;
for (int i=0;i<r2;i++)
{
for (int j=0;j<c2;j++)
{
cin >> *(*(mat2+i)+j);
cout << endl;
}
}
cout <<"\n\n\n" <<"The 1st matrix you entered is:- \n";
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cout << *(*(mat+i)+j) << '\t';
}
cout << endl;
}
cout << "\n\n" << "The second matrix you entered is:- \n";
for (int i=0;i<r2;i++)
{ for (int j=0;j<c2;j++)
{
cout << *(*(mat2+i)+j) << '\t';
}
cout << endl;
}
int **mat4;
mat4=(int**)malloc(sizeof(int)*r);
for (int i=0;i<r;i++)
{
*(mat4+i)=(int*)malloc(sizeof(int)*c2);
}
if (c!=r2)
{
cout << "\n\n These two matrices cannot be multiplied as number of
columns("<< c<< ")of 1st matrix \nis not equal to number of
rows("<< r2<< ") of second matrix.";
}
if( c==r2)
{
for (int i=0;i<r;i++)
{
for (int z=0;z<c2;z++)
{
for (int j1=0;j1<r2;j1++)
{
mat4[i][z]+= mat[i][j1] * mat2[j1][z]; /* logic to
multiply two matrices */
}
}
}
for (int i=0;i<r;i++)
{
for (int j=0;j<c2;j++)
{
cout << mat4[i][j] << '\t';
}
cout << endl;
}
}
return (1);
}
当我输入2x2和2x3矩阵或c2 = c + 1的任何组合时,就会出现问题。我在输出中得到随机大数。否则,如果我输入行数和列数的任何其他组合,则效果很好。例如-如果我把r2 = 3和c2 = 4放进去,无论我做什么输入,我都会在第1列和第3列得到荒谬的值。