class Matrix2 that stores two dimensional matrix

Hello guys,

I'm a beginner in c++ and i stumbled upon a problem. I have to define a class Matrix2 that stores two dimensional matrix, by keeping its elements in a dynamically allocated array of integers (int **a;).

I have come up with this code. Is this correct?

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
class Matrix2{

 int **p2DArray;
 const int Rows = 50;
 const int Cols = 2;
public:

 // Constructor
 Matrix2() {
  // Allocate Memory
  p2DArray = new int*[Rows];
  for (int i = 0; i < Rows; ++i)
    p2DArray[i] = new int[Cols];
 }

 // De-Constructor
 Matrix2() {
  // De-Allocate so we don't have memory leak
  for (int i = 0; i < Rows; ++i)
   delete [] p2DArray[i];

  delete [] p2DArray;
 } 

 // Do Something
 void doSomething() {
  p2DArray[someRow][someCol] = 12;
 }
}
You don't want Rows and Cols to be const since dynamic size is the whole point. Those sizes will need to be passed in to the constructor.

1
2
3
4
5
Matrix2( int rows, int cols )
  : Rows(rows), Cols(cols)
{
    // ...
}


Another way to allocate the memory is to allocate one chunk of integers like this:

1
2
3
4
5
6
7
8
9
10
11
// Declare
int* p2DArray;

// Allocate
p2DArray = new int*[ Rows * Cols ];

// Acccess
int n = p2DArray[someRow * Cols + someCol]

// Deallocate
delete[] p2DArray;


That's particularly good if you're allocating/deallocating a lot, since it's just one big chunk instead of a bunch of rows.
thanks for your reply.

And how can I demonstrate with this class:

the difference between initialization
1
2
        Matrix2 s;
        Matrix2 t = s;


and assignment

1
2
3
     Matrix2 s;
        Matrix2 t;
        s = t;



?
Last edited on
What do you have so far?
I got nothing. That's why I'm asking what is the difference.
Topic archived. No new replies allowed.