Multidimensional Arrays

Multidimensional Arrays

The 80x86 hardware can easily handle single dimension arrays. Unfortunately, there is no magic addressing mode that lets you easily access elements of multidimensional arrays. That's going to take some work and lots of instructions.

Before discussing how to declare or access multidimensional arrays, it would be a good idea to figure out how to implement them in memory. The first problem is to figure out how to store a multi-dimensional object into a one-dimensional memory space.

Consider for a moment a Pascal array of the form "A:array[0..3,0..3] of char;". This array contains 16 bytes organized as four rows of four characters. Somehow you've got to draw a correspondence with each of the 16 bytes in this array and 16 contiguous bytes in main memory. Figure Mapping a 4x4 Array to Sequential Memory Locations The actual mapping is not important as long as two things occur: (1) each element maps to a unique memory location (that is, no two entries in the array occupy the same memory locations) and (2) the mapping is consistent. That is, a given element in the array always maps to the same memory location. So what you really need is a function with two input parameters (row and column) that produces an offset into a linear array of sixteen memory locations. Now any function that satisfies the above constraints will work fine. Indeed, you could randomly choose a mapping as long as it was unique. However, what you really want is a mapping that is efficient to compute at run time and works for any size array (not just 4x4 or even limited to two dimensions). While there are a large number of possible functions that fit this bill, there are two functions in particular that most programmers and most high level languages use: row major ordering and column major ordering.

Example

Creating a multidimensional array.

#include <iostream.h>
int main()
{
int SomeArray = { {0,0}, {1,2}, {2,4}, {3,6}, {4,8}};
for (int i = 0; i<5; i++)
{
for (int j=0; j<2; j++)
{ cout << "SomeArray[" << i << "][" << j << "]: ";
cout << SomeArray[i][j]<< endl;
}
}
return 0;
}

Output:

SomeArray: 0 SomeArray: 0 SomeArray: 1 SomeArray: 2 SomeArray: 2 SomeArray: 4 SomeArray: 3 SomeArray: 6 SomeArray: 4 SomeArray: 8