2D arrays with variable indexes

This is a discussion on 2D arrays with variable indexes within the C++ Programming forums, part of the General Programming Boards category; I'm writing a program (a random map generator, to be exact) that requires a 2D array to created base on ...

2D arrays with variable indexes

I'm writing a program (a random map generator, to be exact) that requires a 2D array to created base on two variables (for the map), height and width. These variables are to be decided at runtime, but the strange way of creating a pointer to a 2D array on the heap has me stumped since the lesser index has to be known. How would I do this with both indexes to be decided at runtime?

The most common cause of this is trying to access memory that doesn't belong to you. For example, reading 1 past the end of an array.

I'd also point out that 2d arrays aren't pretty. You'll need to write functions to create and destroy the array, and the syntax for passing 2d arrays to functions is clunky.

There are two ways to deal with this. If you just need something that works, the vector of vectors is by far the simplest solution. If you want to get a feel for 2d arrays, writing a class (matrix or grid or some such) is a good exercise, as it really begs for encapsulation.

While I was writing this post, I thought of the problem. I was trying to access the array in a function I never passed it to (at least I think that's what the problem is). The code is 2500 lines long anyway, so I don't think anyone wants to look at it. If that's not the problem, I'll post the code for you guys to take a look at.

I got it to work, but I want to be able to understand it. Tell me if I'm wrong in any of these.

Code:

int** array = new int*[x];

This declares a pointer to a pointer and then initializes it to point to the first element of an array of pointers (the array having x elements).

Code:

for(int i = 0; i != x; ++i)
array[i] = new int[y];

This assigns the pointer that array[i] points to to an array with i elements.

Code:

(*(*(array+i)+j)) = 5;

This dereferences array (along with adding an offset before the dereference), to access the pointer pointed to by (array+i). Each element of array holds a pointer that holds the address of an int array on the heap so further applying the dereference operator on and adding an offset to array (array[i][j]) dereferences the pointer pointed to by array[i] and accesses the element array[i][j].

I have a hunch this is right. I didn't do any research, this is just an educated guess. I'm fairly good with pointers already, just not pointers to pointers.