#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);
}
The problem occurs when I enter a 2x2 and a 2x3 matrix or any combination with c2=c+1. I get random large number in the output. Else if I enter any other combination of number of rows and columns, it works just fine. For example- If I put r2=3 and c2=4 , I'll get absurd values at column 1 and 3 no matter what input I do.