init 2-dim array with unknown length

Hello!
Just started c++, got some experience from java, arrays were alot easier there.

I want to make a Class and initialize a 2 dimensional int array there, but the length of each dimension should be declared in the constructor.
unfortunately i dont know how to initialize an 2-dim array without specifying its length... like int x[][]; doesnt work. :(

maybe someone can show me, coudlnt find anything helpful on web. :)
Kaisky

1
2
3
4
5
6
7
8
9
10
11
class Matrix {
public:
	Matrix(int, int);
	int dimX, dimY;
	int x[dimX][dimY]; // of course this doesnt work
};

Matrix::Matrix(int dimx, int dimy) {
	dimX = dimx;
	dimY = dimy;
}


edit:
also i would like to set dimX and dimY to const int, but then i cant set it in the constructer anymore :(
Last edited on
Allocate the data (what you call 'x') as a single dimensional, dynamic array.
Create a private function to turn an (x,y) pair into an index into that array.
Use it to access data.

Hope this helps.
thank you! worked for me :)

how do i declare dimX, dimY as const?
Don't. Make accessors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <algorithm>

class Matrix {
public:
	Matrix(int dimX, int dimY):
		_dimX(dimX<1?1:dimX),
		_dimY(dimY<1?1:dimY),
		_data(new int[dimX()*dimY()])
	{
		std::fill_n(_data, dimX()*dimY(), 0);
	}

	~Matrix()
	{
		delete[] _data;
	}

	int dimX() const { return _dimX; }
	int dimY() const { return _dimY; }
	...
private:
	int _dimX, _dimY;
	int* _data;
};

Hope this helps.
Topic archived. No new replies allowed.