Sunday, May 29, 2011

Multi dimensional array access

Problem


Lets say I manually input an array in my c++ code in the following manner

int matrix = { { {1,12,13,1}, {0,3,1,1} }, { {51,7,64,4}, {51,64,2,3} } };

I had a hard time figuring out which entry I was accessing. When I typed something like:
matrix[1][1][3]

Solution

Its actually quite simple since there is a logic to this. You see, between the first square brackets is a call to the widest set of curly braces, the second is the smaller set and the third is the smallest.

matrix[big][smaller][smallest]

to explain this let me use an image.

 

As you can observe matrix[1][1][3] = 3