Multi-Dimensional Arrays using a Single Array

Blitz3D Forums/Blitz3D Programming/Multi-Dimensional Arrays using a Single Array

Techlord(Posted 2004) [#1]
In developing the BlitzScript3D Engine, I've worked out the math to convert multiple indexes into a linear index for use with Single Dimension Arrays (ie: mytype.alien[100]).

Although you'll rarely use more than four dimensions, the code snippet below, illustrates the formula that will compute the linear index for an array with any number of dimensions:
Graphics 1024,768
n=Input("Number of Array Dimensions: ")
ascii= 96
element$=Chr(ascii+loop+1)
dimensions$="a"
For loop = 1 To n
	Print "Dim Array("+dimensions+")"
	Print "linear_index=base_index+"+String("(",loop)+"a_index)" + expressions$ + "*element_size_in_bytes"
	Print 
	element$=Chr(ascii+loop+1) 
	expression$="*"+element$+"_size+"+element$+"_index)"
	expressions$=expressions$+expression$
	dimensions$=dimensions$+","+element$
Next
I've tossed an excerpt from the BlitzScript Engine Source into the Code Archives for Blitz3D, Blitz+, and BMax users. The code demonstrates how you can apply the formula to create multi-dimensional arrays with a single dimension array.

There is no magic addressing mode that lets you easily access elements of multidimensional arrays. They require some work and lots of instructions even at the compiler level. This formula is employed by most high level programming languages including Pascal, C/C++, Java, Ada, Modula-2, etc. Hope someone finds it useful.