C 循环通过阵列MIPS程序集

C 循环通过阵列MIPS程序集,c,arrays,assembly,while-loop,mips,C,Arrays,Assembly,While Loop,Mips,我正在做一个程序,它循环通过一个由10个数字组成的数组。前9个元素的值大于0,第10个元素的值为0。遇到0时,循环应中断 i=0; while(A[i]!=0) { A[i]=A[i]+1; i++; } 我知道如果寄存器的值等于0,我可以使用“beq”来中断循环。然而,我对如何处理内存中的值知之甚少 这是我第一次使用MIPS,你会看到它一团糟。如果你不能帮我修好,你能给我一些建议吗 .data #by default, the "data segment" starts a

我正在做一个程序,它循环通过一个由10个数字组成的数组。前9个元素的值大于0,第10个元素的值为0。遇到0时,循环应中断

i=0;
while(A[i]!=0)
{
    A[i]=A[i]+1;
    i++;
}
我知道如果寄存器的值等于0,我可以使用“beq”来中断循环。然而,我对如何处理内存中的值知之甚少

这是我第一次使用MIPS,你会看到它一团糟。如果你不能帮我修好,你能给我一些建议吗

.data  #by default, the "data segment" starts at address 0x10010000
.word 1
.word 2
.word 3
.word 4
.word 5
.word 6
.word 7
.word 8
.word 9
.word 0

.text #instructions start below

# MIPS assembly code

lui  $a0, 0x1001           # $a0 = 0x10010000
addi $a1, $zero, 0         # i = 0
jal increment              # call the procedure
这是我最迷路的地方:

increment:
lui $a0, 0x1001           # $a0 = 0x10010000
beq $a0, $zero, else      # if $a0 holds 0 goto 'else'
addi $a0, $a0, 2          # +2
addi $a1, $zero, 1        # i = i + 1

jr $ra                   #jump to caller
$v0应保存所有递增值的总和

else: 
add $a0, $v0, $zero #copy result as input to syscall
addi $v0,$zero,1 #service 1 for syscall is print integer
syscall
以无限循环结束

infinite: j infinite

要从内存加载值,需要调用加载指令之一(
lw
lh
lb
,用于字、半字和字节)。例如:

lw $a1, 0($a2) # load a word from the address in $a2 + offset 0 to $a1
sw $a1, 0($a2) # store the word in $a1 into the address in $a2 + offset
要在内存中写入值,请使用其中一个store命令,例如:

lw $a1, 0($a2) # load a word from the address in $a2 + offset 0 to $a1
sw $a1, 0($a2) # store the word in $a1 into the address in $a2 + offset
例如,使用la将地址加载到寄存器中

la $a2, label_of_array # load the address of the label 'label_of_array' into $a2
现在,要操作数组中的值,需要组合上面的三条指令:

la $a1, label_of_array   # load the address of the array into $a1
lb $a2, 0($a1)           # load a byte from the array into $a2
addi $a2, $a2, 1         # increment $a2 by 1
sb $a2, 0($a1)           # store the new value into memory
addi $a1, $a1, 1         # increment $a1 by one, to point to the next element in the array
还有一点:


您编写了
addi$a1,$zero,1#i=i+1
,但这是错误的。您所做的是将
$zero+1
的结果(即
1
存储到
$a1
中。为了增加
$a1
,您需要编写
addi$a1,$a1,1
,它是“将
$a1+1
的结果存储到
$a1

您说$v0应该保存所有递增值的总和,但这不是C代码所做的。它将数组中的所有值递增1。你想要哪一个?这两个都是真的,循环将值递增1,而$v0存储所有递增值的总和。因此,如果它能工作,也许我可以在循环中添加1后,将新值添加到$v0。谢谢,这很有帮助。但是如何增加数组每个循环的偏移量,或者有效地使用索引?编辑:别担心,我看到了。不要增加偏移量,增加保存数组地址的寄存器(如我发布的代码示例的最后一行)是的,只是注意到了。谢谢