[英]Array indexing in a for-loop in MIPS assembly
I need to implement this code in the MARS emulator: 我需要在MARS模拟器中实现以下代码:
int x[10] = { /* initial values */ } ;
int i;
for(i=0; i<10; i++){
print i;
}
for (i=0; i<10; i++){
x[i] = 2*i+1;
print x[i];
}
Heres what I have: 这是我所拥有的:
.data
i: .word 0
x: .word 1,2,3,4,5,6,7,8,9,10
.align 2
.text
.globl main
main:
lw $t0, i
lw $t1, x
li $t4, 4
jal L0
li $t0, 0
jal L1
li $v0, 10 # terminate
syscall
L0:
li $v0, 1
la $a0, ($t0)
syscall
addi $t0, $t0, 1
bge $t0,10, RETURN #goto L1 if NOT n<0
b L0
L1:
li $v0, 1
la $a0, ($t1)
syscall
mul $t2, $t0, $t4
lw $t1, x + ($t2) #########this line#########
addi $t0, $t0, 1
bge $t0,10, RETURN
b L1
RETURN:
jr $ra
I commented next to the line that I believe to be the source of my problem. 我在我认为是我的问题根源的那行旁边发表了评论。 That is essentially the line that is referencing x[i].
实质上,这是引用x [i]的行。 I multiplied i by 4 and added that value to x, in attempt to reference the appropriate word in the array.
我将i乘以4,然后将该值加到x,以尝试引用数组中的适当单词。 I don't know how to properly implement this concept.
我不知道如何正确实施这个概念。
Thanks for the help. 谢谢您的帮助。
You need to do something like this: 您需要执行以下操作:
L1:
la $a1,x # $a1 = &x
L2: # do {
addu $a0,$t0,$t0 # $a0 = i*2
addiu $a0,$a0,1 # $a0 = i*2 + 1
sw $a0,($a1) # x[i] = i*2 + 1
addiu $a1,$a1,4 # a1 = &x[i+1]
li $v0,1 # print_int
syscall # print_int(i*2 + 1)
addiu $t0,$t0,1 # i++
bne $t0,10,L2 # } while (i != 10)
jr $ra
And stuff like la $a0, ($t0)
looks really weird. 像
la $a0, ($t0)
这样的东西看起来真的很奇怪。 Please use the much clearer move $a0, $t0
instead. 请使用更清晰的
move $a0, $t0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.