[英]C array indexing in MIPS assembly?
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
?我的问题是为什么 int
v[]
被添加$t1
? (whoever did this didn't even comment it so I'm assuming $a0
is v[]
and $a1
is k
). (这样做的人甚至没有评论它,所以我假设
$a0
是v[]
并且$a1
是k
)。
Answer in mips:以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
?我知道这用于交换变量,但它在这里做什么,为什么要添加
v[]
和k
? Isn't v[]
a array of declared variables, how can you add it with a integer k
?不是
v[]
一个声明变量的数组,你怎么能用整数k
添加它?
whoever did this didn't even comment it so I'm assuming $a0 is v[] and $a1 is k
这样做的人甚至没有评论它所以我假设 $a0 是 v[] 而 $a1 是 k
These are the MIPS calling conventions .这些是 MIPS调用约定。 First 4 arguments of a function are in
$a0..$a3
and return value (not required here) is in $v0
(and $v1
if required).函数的前 4 个参数在
$a0..$a3
,返回值(此处不需要)在$v0
(如果需要,还有$v1
)。 Return address is in register $ra
.返回地址在寄存器
$ra
。
I know this is used to swap variables but what is it doing here, why is it adding v[] with k?
我知道这用于交换变量,但它在这里做什么,为什么要添加 v[] 和 k? isnt v[] a array of declared variables, how can you add it with a integer k?
v[] 不是一个声明变量的数组,你怎么能把它加上一个整数 k?
v[] is indeed an array of int. v[] 确实是一个 int 数组。 What holds variable v is the address of the array.
保存变量 v 的是数组的地址。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.