I was trying to find out a simple way to navigate through the multidimensional array, and understand it. And i decided to develop some simple technique which would let treat complicated arrays. As an example lets say i have the following array
ar[2][2][2][2] as you see it is a 6 dimensional array.
Well, two dimensional array is just a grid... 3 dimensional array could be imagined like a cube...but when there are more dimensions, then its more difficult to imagine it and navigate through it. Of course i can always create some pointer and navigate through it like this:
int *p = &ar[0][0][0][0];
and then i can just manipulate with a pointerm, *(p+offset).
But i can also imagine any multidimensional array as a tree... the first top element of tree is a name of array, then i do this: in case of ar[2][2][2][2], i see first number in first bracket from left is 2, so it has two elements, then i draw two elements under the first top element of tree, the next number in next brackets is 2, it means that each two elements have two elements...i draw them under each of them...and so on...
now i can access to the first element of the array with this ****ar, and i see that the number of '*' stars must equal the number of dimension the array has. And to access the next element i put ( after the first star from the left, then put +offset to the end, and then close with ), so... the 7th element is, *(***ar + 7).
I also see that now i can navigate through this tree by moving in all 4 directions through this tree, and now i can access to the element with index 7 in different ways... here is a code..
So the point is to use a tree as a map for any type of multidimensional array... of course probably you wont need these to use in practice, but it just can give another quick help in imagination of such an array..Code:#include <stdio.h> void main (int argc, char *argv[]) { int ar[2][2][2][2] = {{{{2,4}, {6,8}}, {{10,12}, {14,16}}}, {{{18,20}, {22,24}}, {{26,28}, {30,32}}}}; int x; x = *(***ar+7); x = *(**ar[0]+7); x = *(*(*(ar[0]+2)-1)+1); x = *(*(*(*ar+1)+1)+1); x = *(***(ar+1)-1); printf("%d",x); }
But one thing which i want to ask the experienced programmers is... can i always be sure that any of such kind of addressing will work? Because some man said to me, that it will work only if all the elements of this multidimensional array would lay down in memory continiously one after another... But aren't they contiguous in case of array?
Right now, in this program, all those expressions of x = give value of 16. the 7th element. So, can i always be sure that any of those expressions will work ALWAYS?
thanks