问题
Question:
void swap (int v[], int k)
{
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
My question is why does int v[]
get added $t1
? (whoever did this didn't even comment it so I'm assuming $a0
isv[]
and $a1
is k
).
Answer in mips:
swap: sll $t1, $a1, 2
add $t1, $a0, $t1
lw $t0, 0($t1)
lw $t2, 4($t1)
sw $t2, 0($t1)
sw $t0, 4($t1)
jr $ra
I know this is used to swap variables but what is it doing here, why is it adding v[]
with k
? Isn't v[]
a array of declared variables, how can you add it with a integer k
?
回答1:
whoever did this didn't even comment it so I'm assuming $a0 is v[] and $a1 is k
These are the MIPS calling conventions. First 4 arguments of a function are in $a0..$a3
and return value (not required here) is in $v0
(and $v1
if required). Return address is in register $ra
.
I know this is used to swap variables but what is it doing here, why is it adding v[] with k? isnt v[] a array of declared variables, how can you add it with a integer k?
v[] is indeed an array of int. What holds variable v is the address of the array. Adding a value to an array address is the way to go to specific elements of the array.
swap: # void swap (int v[], int k)
; so v[] is in $a0 and k in $a1
sll $t1, $a1, 2 ; k*=4 (ie sizeof(int))
add $t1, $a0, $t1 ; $t1=@v+4*k==@(v[k])
lw $t0, 0($t1) # temp = v[k];
lw $t2, 4($t1) ; 4(t1) is @(v[k])+4==@(v[k+1]
; $t0==temp==v[k], $t2==v[k+1]
sw $t2, 0($t1) # v[k] = v[k+1];
sw $t0, 4($t1) # v[k+1] = temp;
jr $ra ; go back to caller
来源:https://stackoverflow.com/questions/54721000/c-array-indexing-in-mips-assembly