need help with creating an m x n matrix
I need help to creater allocate space.
Here is what I have
Code:
class Array
{
friend ostream &operator<<( ostream &, const Array & );
friend istream &operator>>( istream &, Array & );
public:
Array( int = 10,int =10 );
Array( const Array & );
~Array();
// inequality operator; returns opposite of == operator
bool operator!=( const Array &right ) const
{
return ! ( *this == right ); // invokes Array::operator==
} // end function operator!=
// subscript operator for non-const objects returns modifiable lvalue
int &operator[]( int );
// subscript operator for const objects returns rvalue
int operator[]( int ) const;
private:
int size, m,n; // pointer-based array size
int a[10][10]; // pointer to first element of pointer-based array
}; // end class Array
My code so far
Code:
#include <iostream>
#include <iomanip>
using namespace std;
#include "array.h"
Array::Array( int m, int n )
{
size = ( m*n > 0 ? m*n : 10 ); // validate arraySize
a[m][n] =*new int[size]; // create space for pointer-based array
for ( int i = 0; i < m ;i++ )
for ( int j = 0; j <n; j++ )
a[ i ][j] = 0; // set pointer-based array element
}
Array::~Array()
{
delete *[]a;
}
Array::Array( const Array &arrayToCopy )
: size( arrayToCopy.size )
{
a[m][n]= *new int[ size ];
for (int i = 0; i < n; i++ )
for (int j = 0; i < m; j++ )
a[ i ][j] = arrayToCopy.a[ i ][j];
}
int main()
{
Array mat1;
Array mat2(4,5);
}
When I run it, it runs ok . But if I implement the destructor , it crashes. I think my memory allocation for a is probably screwy too.. Helpl
Re: need help with creating an m x n matrix
You need not delete a, ( delete *[]a;) in the dtor. You have declared a as int a[10][10]; which is allocated on stack and not heap.
Also your whole program seems to be of wrong concepts. I would suggest you refer some good C++ / Data structure book and try some example from it.
One more thing, if you are practising arrays, then fine. Else theres QList class in Qt for such things.
Re: need help with creating an m x n matrix
I am doing an overloading operator exercise from C+ How To Program using multidimension array. I am starting with his Array example and modifying it.
Re: need help with creating an m x n matrix
As long as you do not deal with very big matrices, It does not make much sense to fall back to the C-style arrays in favor of the C++-style collections from either the STL or Qt's own container classes. To implement a matrix I suggest to use QVectors and have a vector of vectors to implement the two dimensions. Depending on your application, you can decide wether to have a list of rows or a list of columns.