问题
What is the following C code in MIPS?
f = A[B[i]]
I'm told it can be done in 6 lines but can't quite figure out how.
f
is in $t0
, i
is in $t3
, A[]
is in $s0
, and B[]
is in $s1
. All types are integer.
The best I am able to think of is
lw $t5, $t3($s0); # Doesn't work because lw syntax doesn't accept a register as an offset
lw $t6, $t5($s1);
sadd $t0, $t6, $zero
Obviously this is wrong. How would i go about getting the correct offset for each line?
Thanks.
回答1:
There might be more efficient ways, but here's one way in 6 lines:
sll $t2,$t3,2 # t2 = i * sizeof(int)
addu $t2,$t2,$s1 # t2 = &B[i]
lw $t0,0($t2) # t0 = B[i]
sll $t0,$t0,2 # t0 *= sizeof(int)
addu $s0,$s0,$t0 # s0 = &A[B[i]]
lw $t0,0($s0) # t0 = A[B[i]]
Read a MIPS instruction set reference to get more information about what individual instructions do.
来源:https://stackoverflow.com/questions/18921044/mips-array-in-array-index