要从内存加载值,您需要调用加载指令之一,(lw
, lh
or lb
对于字、半字和字节)。例如:
lw $a1, 0($a2) # load a word from the address in $a2 + offset 0 to $a1
要在内存中写入一个值,您可以使用存储命令之一,例如:
sw $a1, 0($a2) # store the word in $a1 into the address in $a2 + offset
将地址加载到寄存器中是使用 la 完成的,例如
la $a2, label_of_array # load the address of the label 'label_of_array' into $a2
现在,要操作数组中的值,您需要组合上面的三个指令:
la $a1, label_of_array # load the address of the array into $a1
lb $a2, 0($a1) # load a byte from the array into $a2
addi $a2, $a2, 1 # increment $a2 by 1
sb $a2, 0($a1) # store the new value into memory
addi $a1, $a1, 1 # increment $a1 by one, to point to the next element in the array
还有一点:
你写了addi $a1, $zero, 1 # i = i + 1
但这是错误的。你所做的就是存储结果$zero + 1
这是1
into $a1
。为了增加$a1
,你需要写addi $a1, $a1, 1
这是“存储结果$a1 + 1
into $a1
.