Level 4, lesson 6

# 4.6 Multidimensional arrays

We've seen two dimensional arrays with 'ARRAY' and 'STRING', but what about multi-dimensional arrays. Well, it's the same thing all over again. C doesn't actually have multi-dimensional arrays either. When you define one, just a chunk of memory is allocated.

In 4tH you can do the same thing, but now you have to do it yourself. E.g. when you want to define a matrix of cells of 4 rows by 5 elements, you have to multiply those and allocate an array of that size (in this case one of 20 cells):

         20 array (my_array)

But what if you want to refence the fourth element of the third row? You cannot write something like:

         2 3 (my_array) @

That's right. But you can wrap "(MY_ARRAY)" into a word that can:

         : myarray                  ( n1 n2 -- a)
               swap 5 *             \ calculate row offset
               +                    \ calculate element offset
               cells                \ caluclate number of cells
               (myarray) +          \ add to address of (myarray)
         ;

This word calculates the correct offset for you. Note that the third row is row number two (since we start counting from 0) and the fourth element is element number three:

         2 3 my_array @

You can also use "MY_ARRAY" to initialise an array, since it simply calculates the correct address for you:

         5 2 3 my_array !           \ sets 3rd row 4th element to 5

You can add more dimensions if you want. This works basically the same way: create an array of a size that equals the products of its dimensions and design a word that calculates the correct address.