Referencing Arrays 

Element referencing:

Each element in an array is referenced with an index number.
The first element in an array is the element whose reference is zero.
The array index appears in brackets after the array name, (e.g. in array[9])

Element index vs. element position:

Assembly-language indexes differ from indexes in high-level languages. In high level languages the index number always corresponds to the element’s position. In C, for example, array[9] references the array’s tenth element, regardless of the size in bytes of each element.

In assembly language, an element’s index refers to the number of bytes between the element and the start of the array. This distinction can be ignored for arrays of byte-sized elements, where an element’s position number matches its index.

For example, the array wprime defined as:

	prime BYTE 1, 3, 5, 7, 11, 13, 17
gives the value 1 for prime[0], the value 3 for prime[1], and so forth.

However, in arrays with elements larger than 1 byte, index numbers (except zero) do not correspond to an element’s position.

Calculating the element's position

In order to determine the element’s index, the element’s position must be multiplied by its size .

For instance, for the array wprime defined as follows:

	wprime WORD 1, 3, 5, 7, 11, 13, 17
wprime[4] represents the third element (5), which is 4 bytes from the beginning of the array.
Similarly, the expression wprime[6] represents the fourth element (7) and wprime[10] represents the sixth element (13).

In the following example the index is determined at run time. The element's position is multiplied by two (the size of a word element in bytes) by shifting it left:

	mov si, cx		; CX holds position number
	shl si, 1 		; Scale for word referencing
				; Similar to: SI = SI x 2 
	mov ax, wprime[si] 	; Move element into AX

As a general rule, the offset required to access an array element can be calculated as follows:

position of nth element of array = array[ (n - 1) * size of element ]

Referencing array elements by distance, rather than position, is actually very consistent with how assembly language works.

A variable name is a symbol that represents the contents of a particular address in memory.
Thus, if the array wprime begins at address DS:2400h, the reference wprime[6] means:

	the value of the word variable contained in the DS 
	segment at offset: 2400h + 6 = 2406h.


The plus operator (+) can be used instead of brackets, as in:



When referencing the first element in an array, brackets are not needed. Thus, wprime and wprime[0] both refer to the first element of the array wprime.