## Accessing Array Data in MIPS

Since arrays can store LOTS of data, and since we have only a small (~32) number of registers, it is infeasible to use the registers for long-term storage of the array data.  Hence, arrays are stored in the Data Segment of a MIPS program.  Fundamentally, there are three operations which one can perform on an array:

• Getting the data from an array cell, e.g, x = list[i];
• Storing data into an array cell, e.g. list[i] = x;
• Determining the length of an array, i.e. list.length.

For purposes of this step in the lab, you may assume that the length of the array is 10.  (The worksheet asks about changing this, but you may hard code this value while writing the program.)

To access the data in the array requires that we know the address of the data and then use the load word (lw) or store word (sw) instructions.  Words (which is how integers are stored) in MIPS take up 32 bits or 4 bytes. Therefore, if we have a declaration such as:

list: .word 3, 0, 1, 2, 6, -2, 4, 7, 3, 7

the address that is loaded by the instruction la \$t3, list is the address of the first '3' in the list.  The address of the '0' is 4 greater than that number, and the address of the '6' is 16 greater than that number.

The following snippet of code will place the value of list[6] into the \$t4:

la \$t3, list         # put address of list into \$t3
li \$t2, 6            # put the index into \$t2
add \$t2, \$t2, \$t2    # double the index
add \$t2, \$t2, \$t2    # double the index again (now 4x)
add \$t1, \$t2, \$t3    # combine the two components of the address
lw \$t4, 0(\$t1)       # get the value from the array cell

If we wish to assign to the contents of \$t4 to list[6] instead, the last line would simply be:

sw \$t4, 0(\$t1)      # store the value into the array cell