你好我是MIPS汇编语言的新手,我试着编写等价的B[8]=A[i-j]
,其中变量f,g,h,i和j分配给寄存器$ s0,$ s1,$ s2,$分别为s3和$ s4。我假设数组A和B的基地址分别在寄存器$ s6和$ s7中。
我的代码
# Gets A[i-j]
sub $t1, $s3, $s4
sll $t1, $t1, 2
add $t1, $s6, $t1
lw $t0, 0($t1)
# Set B[8] equal to above
addi $t2, $s0, 8
sll $t2, $t2, 2
add $t2, $s7, $t2
lw $t2, 0($t2)
sw $t2, 0($t0)
但是这会在0x0040000c处抛出运行时异常:地址超出范围0x00000000,有什么建议吗?
答案 0 :(得分:2)
# Gets A[i-j]
sub $t1, $s3, $s4
sll $t1, $t1, 2
add $t1, $s6, $t1
lw $t0, 0($t1)
# Set B[8] equal to above
addi $t2, $s0, 8 #this actually computes something like &B[f+8], not &B[8]
sll $t2, $t2, 2
add $t2, $s7, $t2
lw $t2, 0($t2) #this loads the value B[f+8]
sw $t2, 0($t0) #this stores B[f+8] to *(int *)A[i-j], which is probably not an address.
如果您希望代码符合您的描述,则必须:
# Gets A[i-j]
sub $t1, $s3, $s4
sll $t1, $t1, 2
add $t1, $s6, $t1
lw $t0, 0($t1)
# Set B[8] equal to above
addi $t2, $zero, 8
sll $t2, $t2, 2
add $t2, $s7, $t2
##deleted##lw $t2, 0($t2) no need to load B[8] if you just want to write to it
sw $t0, 0($t2) #this stores A[i-j] to &B[8]