Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is simple matrix multiplication using dynamic allocation and without using the concept of friend function. i'm getting segmentation error core dumped...
Plz help

What I have tried:

C++
<pre>#include<iostream>

using namespace std;

class Matrix
{
     int n,m; //n-> row and m-> column
     int** M; //Matrix pointer
public:
     Matrix()
     {
       M=NULL;
     }
     Matrix(int r,int c)  //initializing matrix and its elements
   {
     n=r;
     m=c;
     M=new int* [n]; //dynamic allocation of row pointer
     for(int i=0;i<n;++i)
         M[i]=new int [m]; //dynamic allocation of column pointer
     for(int i=0;i<n;++i) //loop for  initializing the values
     {
         for(int j=0;j<m;++j)
            {
                  cout<<"\n ENTER ELEMENT "<<i<<","<<j<<" OF MATRIX :- ";
                  cin>>M[i][j];
               cout<<"\t"<<M[i][j];
            }
     }
   }
    void Change(int,int); //Change the dimensions of the current Matrix
    int Multiply(Matrix &M1, Matrix &M2); //Matrix Multiplication
    void Display(); //Display the Matrix elements
int ret_r() //return no. of rows
  {
      return n;
  }
    int ret_c() //return no. of columns
   {
      return m;
   }
   int** ret_m() //return Matrix
 {
  return M;
 }

~Matrix() //Destructor to deallocate heap memory
{
 delete M;
}
};

int main()
{
  Matrix m1(2,3); //Matrix 2*3
  Matrix m2(3,2); //Matrix 3*2
  Matrix M; //Matrix to store result
  M.Multiply(m1,m2); //Matrix Multiplication call
return 0;
}

void Matrix::Change(int r,int c)
  {
       n=r;
       m=c;
       M=new int* [n];
       for(int i=0;i<n;i++)
        M[i]=new int [m];
  }// Rows & columns change

int Matrix::Multiply(Matrix &M1, Matrix &M2)
{
   int c1=M1.ret_c();
   int r2=M2.ret_r();
   if(c1==r2)
{   int r1=M1.ret_r();
    int c2=M2.ret_c();
    int** Ma=M1.ret_m();
    int** Mb=M2.ret_m();
     Change(r1,c2);
//to create matrix of appropriate dimensions
    for(int i=0;i<r1;++i)
{
   for(int j=0;j<c2;++i)
{

      M[i][j]=0;
       for(int k=0;k<c2;k++)
{
     M[i][j]+=Ma[i][k]*Mb[k][j];
}
}
}
 Display(); //Display the elements
 return 1;
}
cout<<"\nError !!!";
return 0;
}
void Matrix::Display()
{
for(int i=0;i<n;i++)
{
  for(int j=0;j<m;j++)
{
   cout<<M[i][j]<<"\t";
}
cout<<endl;
}//Display function definition
}
Posted
Comments
Richard MacCutchan 8-Apr-17 3:51am    
You need to use your debugger to find out exactly where the error occurs, and check which variables cause the problem. Most likely an invalid or uninitialised pointer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900