Array flattening
One dimensional arrays, or flat arrays as they are sometimes called, have desirable properties. They are fast. They are simple to access and to iterate through. They can easily be assigned to contiguous memory blocks.
The above picture shows how indexing works when we turn our multi-dimensional array into a flat array.
int index = rowWidth * row + col;
The above code pretty much explains it all. But in case you're like me, and you sometimes have difficulties understanding things until you've studied them thoroughly, I will walk you through the gist of it.
In the example above we have a multi-dimensional 3 x 4
array. 3 rows (0-2) and 4 columns (0-3) and, and we want to find the index for 1,2
in other words, we want the index for row position 1, column position 2, and we want to find that index position in our one dimensional flat array which is essentially emulating a multi-dimensional 3 x 4 array.
We take the width of our rows, ie. their actual size (4 columns wide) and we multiply it with the index of the row that we want to access (1). In other words rowWidth * row
ie. 4 * 1
in our example. This gives us the combined length of all the previous rows of data (because the index starts from 0, we essentially always skip the current one), ie. row 0 is the previous row in this case. 4 * 1 = 4
We have 4 entries in all the previous rows.
Next we want to add our index location on the column to this number. This gives us the final index value. In our example our location on the column is 2, therefore we add 4 + 2 = 6
, giving us the final index of 6.
The explanation is probably harder to follow than the code and picture, but there you have it.