Multi-Dimensional Arrays

An array variable can have several dimensions, up to 32 in VB.NET.  A two dimensional array can be visualised as a table with a horizontal ‘X’ dimension and a vertical ‘Y’ dimension.

2darray1

The command syntax for declaring a 2D array varies slightly from language to language, but for most languages it’s essentially the same.  In Visual Basic the syntax includes a name, the size of each dimension and a data type.  For example, to declare this array with the name People, we would use this command.

Dim People(4,8) As String

Accessing an element of a 2D array is just a matter of specifying the correct co-ordinates.  For example, to assign the value “Foo” to the element with co-ordinates x = 3 and y = 2, you would write:

People(3, 2) = “Foo”

2darray1-2

In the following example, each row of the array contains the details of a famous person.

2darray2

To access each item in turn you need a loop inside a loop.

FOR Y = 0 To 8

     FOR X = 0 To 4

           OUTPUT People(X, Y)

     NEXT X

NEXT Y

Here, we see that the outer loop is visiting each of the 9 rows, one at a time, so we are scanning down the vertical Y dimension of the array.  But for every pass of the outer loop, there are 5 passes through the inner loop.  This means that each element within each row is visited one at a time.

Two dimensional array variables are particularly useful for holding tabular data such as this.  In a real world application, a 2D array such as this might be initialised with data from a database table.

2D arrays in memory

Behind the scenes, as is the case with a one dimensional array, 2 dimensional array data items are stored in contiguous memory locations. Well, sort of!  The computer’s RAM is a linear structure, so two dimensional array data can’t be totally contiguous.  2D array data needs to stored in the RAM either row-wise, or column-wise. Which of these depends on the programming language.

Below we can see the priority was to keep the data in each row contiguous. The programming language that set this up, is said to be row major.  C++, C# and Visual Basic are examples of row major programming languages.

2darray3

The programming language that set up the array below in memory however, is said to be column major.  You can see the priority was to keep the data in each column as close together as possible. FORTRAN is an example of a column major application.

2darray4

Most programmers don’t need to concern themselves with the way array data are physically stored in memory.  However, if you’re trying to eek out every little bit of performance from an application, you may want to know if your language is row major or column major, and how you intend iterate through the data.  This doesn’t mean you have to change your programming language, rather, you might think twice about you declare a 2D array. For example, should you say this?

Dim People(4, 8) As String

or should you say this?

Dim People(8, 4) As String