Search code examples
arraysassemblymipsoffset

MIPS Assembly accessing an array while using a variable as the offset


Is there anyway to use a variable as the offset number for an array? For example, I know the normal offset and array works like this:

ARRAY: .word 0,1,2,3,4,5,6,7,8,9
lw $t6, ARRAY
lw $t7, 0($t6)

Where the index at zero would be loaded into t7, but what I want to do is this:

 ARRAY: .word 0,1,2,3,4,5,6,7,8,9
 lw $t6, ARRAY
 li $t7, 0
 lw $t8, $t7($t6)

This way I could increment the variable t7 as I wanted to in code without having to hard-code the offset. I keep getting a syntax error, so I guess what I am trying to do is wrong. Is there anyway I can do something like this so that I can increment the index of the array?


Solution

  • In order to increment through an array with a variable, you must use this setup:

    ARRAY: .word 1,2,3,4,5,6,7,8,9
    li $t2, 0
    lw $t3, ARRAY($t2)
    addi $t2, $t2, 1