i have written a class to add matrices ,line 51 of the
code has problem.
debugger is showing segmentation fault there .
please suggest the correction.

#include <iostream>
using namespace std;
class mat
{
  int row;
  int column;
  double **a;
public:
  mat(){}
  mat(int r,int c)
  {
    row = r;
    column = c;
    a = new double *[r];
    for (int i = 0;i < r;i++)
    {
      a[i] = new double [c];
    }
  }
  void getvalue(void)
  {
    for (int i = 0;i < row;i++)
    {
      cout << "enter " << i << "th row" << endl;
      for (int j = 0;j < column;j++)
      {
        cin >> a[i][j];
      }
    }
  }
  void putvalue(void)
  {
     cout << "" << endl;
     for (int i = 0;i < row;i++)
     {
       for (int j = 0;j < column;j++)
       {
         cout << a[i][j] << " ";
       }
       cout << "" << endl;
     }
  }
  //define addition opertor
  mat operator+(mat p)
  {
    mat temp;
    for (int i = 0;i < p.row;i++)
    {
      for (int j = 0;j < p.column;j++)
      {
        temp.a[i][j] = a[i][j] + p.a[i][j];
      }
    }
    return temp;
  }
};
int main()
{
  int r,c;
  cout << "enter number of rows and columns " << endl;
  cin >> r >> c;
  mat a(r,c),b(r,c),d(r,c);
  a.getvalue();
  b.getvalue();     
  d = a + b;
  d.putvalue();
  return 0;
}

Recommended Answers

All 4 Replies

What error are you getting? From the look of it you might need to define a operator= for your mat class. Also it is bad coding practice to define large functions inside the class. You should define them outside like

class Foo
{
    //...
    int Bar(int);
    //...
}

int Foo::Bar(int foobar)
{
    //...
}

Line 46: How the memory for temp's data is allocated?

Line 46:

mat temp(row, column);

Edit: Ups, pretty late...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.