I'll share the code block I came up with, using segments from the link above; for anyone in future that is looking for a similar solution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// Working Variables
//---------------------------------------------------------
const int matrixWidth(5); // etc.
const int matrixHeight(3); // etc.
int* iMatrix[matrixWidth * matrixHeight] = {0};
int* ip(iMatrix);
int index(0);
for(int i = 0; i < (matrixWidth - 1); i++)
for(int j = 0; j < (matrixHeight - 1); j++)
{
// Get the index
index = (i * matrixHeight) + j;
// To access matrix element (just an example)
ip[index];
// Do work
// [ ... ]
}
|
Now you'll notice that this doesn't look like a 2D array.
I've created the matrix like "iMatrix[]" and not "iMatrix[][]".
Creating the "matrix" in-line, maximizes the efficiency of the data access and navigation; at the cost of a tiny bit more code.
Not to mention, you can navigate it with a single pointer.
You create enough elements in the in-line array to house your 2D array (i.e. like so: matrixWidth * matrixHeight).
To get the index of an element of the in-line matrix you use this algorithm: "(x-coord * matrixHeight) + y-coord".
To navigate on the x-axis you add/subtract the "x-distance * matrixHeight".
To navigate on the y-axis you add/subtract the "y-distance".
To understand how this works, (if you don't intuitively understand) visualise the array like this:
matrixWidth = 5;
matrixHeight = 3;
[0, 1, 2 | 3, 4, 5 | 6, 7, 8 | 9, 10, 11 | 12, 13, 14]
0, 3, 6, 9, 12
1, 4, 7, 10, 13,
2, 5, 8, 11, 14
I hope this helps someone in the future! ^_^
NOTE: Remember that the index-0 element of an array is the first element in the array. This is important because the X-MAXIMUM and Y-MAXIMUM is the demensions of the matrix -1.
"matrixWidth - 1", "matrixHeight - 1".