Skip to content

3. Arrays

Strings

Strings is an array of characters, in MIPS, they are one byte.

Arrays in Assembly, well, we can't fit them into the very small number of registers available, so we need to use memory! Here is an example of how we store 4-byte values.

Alt text

Suppose we had the array int[] arr = {1, 2, 3}, how do we store values and get them. We use little-endian for each 4 bytes of data. To access/store values, we need to figure out their memory address. Starting at $A$, with each item $b$ bytes long, and the $n$th element: address = $A+(n\cdot b)$.

Alt text

for(int i = 0; i < length; i++)
    print(data[i]);

To access the elements, we will get their address: $\text{address of item i} = \text{base_address} + (\text{index} \cdot \text{sizeof(item i)})$. Or in this code example: $\text{address of item i} = \text{base_address} + (\text{index} \cdot 4)$

MIPS

Let's exit the word of math formulas and definitions, and enter into MIPS. To make an array, you can do it in either of two ways:

.data
    little_array: .word 1, 2, 3, 4
    big_array: .word 0xBEEFC0DE:100 # this fills the array with 100 copies of 0xBEEFC0DE

Ok, now let's load the address.

la t0, little_array

This doesn't actually load anything from memory. It just gives you the address of the little_array. To get/store an element:

la t0, little_array
li t1, 2 # to get 3rd element
mul t1, t1, 4
add t2, t0, t1

lw t0, (t2) # t0 = myArray[2]
add t0, t0, 1
sw t0, (t2) # myArray[2] = myArray[2] + 1

Reuse Registers to Make Code Easier to Keep Track!

Alignment

All memory accesses must be aligned. Alignment is the address of a n-byte value must be a multiple of n.

Alt text

Strings

There are two different types of strings.

.data
    string0: .asciiz "Test" # string: .byte 84, 101, 115, 116, 0
    string1: .ascii "Test"  # string: .byte 84, 101, 115, 116

.asciiz includes the zero terminator. This is usually what you want.

.ascii does not include zero terminator. Strange things happen.

Next Page →