First load the address of the array into a register, then you can access the items with a constant offset. (Your assembler might support constructs such as lw $t0, arr+12
as convenience shorthand for this. See your manual.) For iteration, either increment the address register, or add another register containing the offset. Be sure to account for item sizes. Folling example is for 32 bit mips, adjust as necessary for 64 bit:
.data
arr: .word 2,5,1,3,4
len: .word 5
sum: .word 0
.text
.globl main
main:
la $t0, arr
lw $t1, 12($t0) # load arr[3] using byte offset
li $t1, 3 # index
sll $t1, $t1, 2 # multiply by item size
addu $t1, $t1, $t0 # add base address
lw $t1, ($t1) # load arr[3]
# iteration type 1
# for(i=len, ptr=arr; i != 0; i -= 1, ptr += 1)
# ... use *ptr ...
la $t0, arr
lw $t1, len # load length
loop1:
lw $t2, ($t0) # load item
# process item here
addi $t0, $t0, 4 # add item size to pointer
addi $t1, $t1, -1 # decrement counter
bne $t1, $0, loop1 # if counter != 0, repeat
# iteration type 2
# for(i=0, i != len; i += 1)
# ... use arr[i] ...
la $t0, arr
lw $t1, len # load length
li $t2, 0 # index
loop2:
sll $t3, $t2, 2 # multiply by item size
addu $t3, $t3, $t0 # add base address
lw $t3, ($t3) # load item
# process item here
addi $t2, $t2, 1 # increment index
bne $t2, $t1, loop2 # if index != len, repeat
(note these sample loops do not handle zero length array, add check if necessary)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…