Ok, understand that in conceptual grids, what's "width" and what's "height" can be considered somewhat arbitrary. You actually quite easily represent a 2D grid with a 1-dimensional array ( For serious work I would recommend this actually, Disch has an awesome article about this:
http://www.cplusplus.com/forum/articles/17108/ )
When you create a multidimensional array in the way you describe, here's in a nutshell what you're really doing.
You first have what I think of as the "base" pointer. This pointer allocates an array of all the other pointers, nothing more. Calling this where you define "rows" or "columns" is arbitrary. You can think of it either way.
The elements of this dynamically allocated array of pointers can all be used to allocate their own arrays, and this is where you actually get your interesting data stored.
So, to try to illustrate my point, with this style of MD array, I'll show a visualization two ways.
* = pointer
d = variable/datum
1 2 3 4 5
|
3x3 array - Visualization 1
*0 d0 d1 d2
*1 d0 d1 d2
*2 d0 d1 d2
|
1 2 3 4 5 6
|
3x3 array - Visualization 2
*0 *1 *2
d0 d0 d0
d1 d1 d1
d2 d2 d2
|
Both of these visualizations are essentially the same when it comes to how you access them.
This is just a visualization though. How are these arrays actually stored in memory?
Well, I'll try explain ( note: If anybody see's something wrong please correct me, but this is my understanding of the subject )
First off, that "base" pointer I mentioned allocated an array of pointers, this array of pointers will be contiguous as you probably already know. The significance of this is that the subarrays themselves are also going to be contiguous, hence actually leading all of the data with this MD array to be in one region of the memory, itself contigous. So lets go back to the illustrations. What does it look like in a one-dimensional representation?
*0 d0 d1 d2 - *1 d0 d1 d2 - *2 d0 d1 d2
So, what if we want say, foo[1][2] , from this array, and we want to set it to 4?
(We'll use the name foo now)
General formula for converting foo[a][b]