0
votes

I'm trying to sum two matrix using struct, but it doesn't work.

If this code can be optimized please tell me :D

Compile with:

g++ -O2 -Wall program.cpp -o program

Output:

In file included from /usr/include/c++/4.8/iostream:39:0, from Proy3.cpp:2: /usr/include/c++/4.8/ostream:548:5: note: template std::basic_ostream& std::operator<<(std::basic_ostream&, const unsigned char*) operator<<(basic_ostream& __out, const unsigned char* __s) ^ /usr/include/c++/4.8/ostream:548:5: note: template argument deduction/substitution failed: Proy3.cpp:51:30: note: ‘std::istream {aka std::basic_istream}’ is not derived from ‘std::basic_ostream’ cin << &M2.x[i][j];

Code:

# include < cstdio >
# include < iostream >


typedef struct Matrix
{
    int row, column;
            int x[20][20];
};

Matrix M1,M2;

using namespace std;

int main() {

cout << "Insert size rows: Mat[a]";
cin >> M1.row);

cout << "Insert size of columns Mat[a]";
cin >> M1.column;


cout << "Insert size of rows Mat[b]";
cin >> M2.row;

cout << "Insert size of columns Mat[b]";
cin >> M2.column;

int i, j;

   // Matrix x

    for(i = 0; i <= M1.row; i++)
{
        for(j = 0; j <= M1.column; j++)
        {
        cout << "Insert number for matrix X : \n";
        cin >> M1.x[i][j]
        }
}

       // Matrix y

    for(i = 0; i <= M2.row; i++)
{
        for(j = 0; j <= M2.column; j++)
        {
        cout << "Insert number for matrix Y : \n";
        cin << M2.x[i][j];
        }
}

// Matrix X + Matrix Y

for(i = 0; i <= M1.row; i++)
{
    for(j = 0; j < M1.column; j++)
    {
        cout <<"The sum of " << M1.x[i][j] << " + " <<  M2.x[i][j] << " = " << M1.x[i][j] +  M2.x[i][j] << endl;
    }
}
return 0;

}

2

2 Answers

0
votes
  for(i = 0; i <= M2.M1.row; i++)
 {
    for(j = 0; j <= M2.M1.column; j++)
    {
    cout << "Insert number for matrix Y : \n";
    cin << &M2.M1.y[i][j];   
    }
  }

There is no element as M2.M1.y which you are trying to access. Also why are you declaring M1 inside M2.You could have only one structure and have two instances of it.Something like

struct matrix
{
    int row,column;
    int X[20][20];
};
struct matrix M1,M2;

Now you can input the two matrices.

Also you have to use cin>>a instead of cin>>&a.

Also cin << &M2.x[i][j]; should be

 cin >> M2.x[i][j];
    ^^^^
0
votes

I think the cin state ment should be cin >> &M2.x[i][j]; instead of cin << &M2.x[i][j];