Ah yes, that problem again. I'll use integers for this example.
When you declare a 2d array statically like this:
int arr[4][5];
a continuous block of memory is set aside for it. The 20 memory spaces are contiguous. The quantity
arr
is actually a pointer to an array of 5 integers. When you increase the value of the 1st index by one, say from arr[2][1] to arr[3][1], an address 5 integer spaces ahead is read. When a regular int* is incremented by one the pointer is advanced only one integer space ahead. This is why it is necessary to give the value of the 2nd array dimension when passing a 2d array. The 5 in
arr[][5]
tells the compiler to look ahead 5 spaces when the 1st index is increased.
The dynamically allocated 2d array formed by allocating an array of pointers:
int** ppInt = new int*[4];
followed by separately allocating an array of integers to each pointer:
1 2
|
for(int i=0; i<4; ++i)
ppInt[i] = new int[5];
|
results in space for 5 integers being allocated in 4 different places. Each of the 4 pointers allocated to ppInt point to these different areas of memory. In this case the 1st array index in ppInt[i][j] tells which pointer to refer to.
These are not equivalent array structures. I hope my explanation made sense.
How to fix it? If your functions are going to take an argument
color room[][30]
then you can still allocate dynamically, but you must use a pointer to 30 colors.
1 2
|
color (*room)[30];// a SINGLE pointer to an array of 30 colors
room = new color[rows][30];// allocate the 2d array in one shot.
|
A continuous block of memory will be allocated for rows x 30 colors, just as if you had declared
1 2
|
const int rows = 30;
color room[rows][30];
|
You can now pass room to a function that expects color room [][30].
Don't forget to cleanup! When finished with this array call:
delete [] room;