2D array class !!!!!!!!!!

this is my header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef matrix_h
#define matrix_h

class Matrix
{
public:
	Matrix(int c, int r);//default constructor
	~Matrix();//destructor
	Matrix( const Matrix & M);//copy constructor
	void setMartix(int c, int r);//function for setting the 2D matrix
	int getMatrix();//function to return the matrix
	static int Getcols(int c);//to modify the columns
	static int Getrows(int r);//to modify the rows
	void Print();
private:
	int **array2D;
	static int rows;
	static int cols;
};

#endif


and this the .cpp file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
using namespace std;
#include "matrix.h"

int Matrix ::rows = 2;
int Matrix ::cols = 3;
Matrix::Matrix(int c, int r)
{//allocating memory
	rows = r;
	cols = c;
	array2D= new int*[rows];
	for (int i = 0; i < rows; i++)
	{
		array2D[i] = new int[cols];
		for (int j=0; j < cols; j++)
		{
			array2D[i][j]=0;
		}
	}
}

Matrix::~Matrix()
{//deleteing memory to prevent memory leak
	for (int i = 0; i < rows; ++i)
		delete [] array2D[i];

	delete [] array2D;
} 

Matrix::Matrix( const Matrix & M)
{
	rows = M.rows;
	cols = M.cols;
	array2D= new int*[rows];
	for (int i = 0; i < rows; i++)
	{
		array2D[i] = new int[cols];
		for (int j=0; j < cols; j++)
		{
			array2D[i][j] = M.array2D[i][j];
		}
	}
}

int Matrix ::Getcols(int c)
{
	cols = c;
	return cols;
}
int Matrix ::Getrows(int r)
{
	rows = r;
	return rows;
}

void Matrix ::setMartix(int c, int r)
{
	array2D= new int*[r];
	for (int i = 0; i < r; i++)
	{
		array2D[i] = new int[c];
		for (int j=0; j < c; j++)
		{
			array2D[i][j];
		}
	}
}

void Matrix::Print()
{
	cout<<"The Matrix : ";
	for(int i =0;i<rows;i++)
		for(int j=0;i<cols;j++)
			cout<<array2D[i][j];
}


can anyone help me figure out the error ????
What is the error?

Why is the rows and cols static? If they are static all Matrix objects will share the same cols and rows which you probably don't want.
when i run the program it gives an error
Without knowing what specific error it is that you're getting, the best I could tell you is that if the error is simply a notification that the program has crashed, (a runtime error) you should make sure the loops are not accessing an index of the arrays that does not exist.
when i run the program it gives an error


Since you can't compile this code into an executable (where's the main() function?) and so we don't know what might happen when you run code we don't have, it's hard to help.

In setMatrix you don't deallocate memory before allocating new memory, causing a memory leak.
Topic archived. No new replies allowed.