2D Arrays

So i'm in a C++ class and we need to use a array of things to make a rip off of conway's Game of Life. Normally when yoy ask a person(user) for input to set the size of the array you have to use dynamic memory to create a NEW array, but i can't get it to make a NEW 2d ARRAY, only a single dimension array. Is there a way to create, using the new operator, a 2D array that is not a 2D n * width + y kinda BS?
2D n * width + y kinda BS?


That's the easier way to do it actually...

You would have to use looped new's:

1
2
3
4
int** 2dArray = new int*[5];
for(unsigned int j = 0; j < 5; ++j) {
    2dArray[j] = new int[5];
}


However, I suggest you just make a wrapper class around a 1-d array so you don't have to loop the delete's too (which you will).
+1 to everything firedraco said.


Multidimentional arrays are fugly, troublesome, and cumbersome.

Obligatory link: http://www.cplusplus.com/forum/articles/17108/
I second firedraco and Disch: Multi-arrays aren't worth it!

Anyway, sometimes a man has to do what another man did wrong (legacy libraries..)
The answer to your case is: typedef one row of the array, then allocate an array of the typedef.

1
2
3
	typedef int my_array_row[10];
	my_array_row* onTheHeap = new my_array_row[20];
	onTheHeap[0][0] = 42;


Note how the "10" is a static value. That's one of the evil things of multidimensional arrays.

firedraco wrote:
You would have to use looped new's:

Beware if you do this. What you get is not the same. You simple get an array of pointers to arrays. Memory layout is not going to be continuous.

Ciao, Imi.
PS: Don't forget: The appropiate way of deleting an array is "delete [] x", not "delete x".
Oh, another one: If you don't care about performance, there is a very simple version of getting the so beloved [y][x] - syntax together when you have to input both: rows and columns is this:

1
2
3
4
5
int initialvalue = 0;
int rows = 20;
int columns = 30;
std::vector< std::vector<int> > my_array(rows, std::vector<int>(columns, initialvalue));
my_array[10][5] = 5; // set the 11th row, 6th column. No need for any initialization loop 

This will give you an already initialized (with zero), fully fledged my_array[y][x] - accessable array where you don't have to care about deleting any pointer (vector delete's its own memory).

Ciao, Imi.
PS: Oh, Of course, and there is always boost::multiarray
PPS: The memory layout is not continuous either, so not usable with legacy C libraries.
Last edited on
Topic archived. No new replies allowed.