arrays - 使用while循环遍历数组? - MIPS

标签 arrays loops assembly mips

这个问题在这里已经有了答案:





Translating C function with args to MIPS: loop over an int array and count negatives

(2 个回答)


8 个月前关闭。




我想遍历一个数字数组,如

.word 2,2,2,2,2,2,2,2,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,2

我想确保数组中的所有内容都是值 2。
现在这些是 52 个元素,所以每次我想检查是否所有数组元素都是 2 时。

这就是我到目前为止所做的:
add $t6,$0,$0
add $t7,$0,$0
SL:
addi $t6,$t6,4
addi $t7,$t7,1
la $t1,array
add $t1,$t1,$t6
lw $s0,($t1)
j check

slti $t8,$t7,52
bnez $t8,SL
jr $ra
check:
li $t3,2
seq $t4,$s0,$t3
beqz $t4,do_something
bnez $t4,exit
jr $ra

但是当我制作这样的数组时
   .word 0,2,2,2,2,2,2,0,2,2,2,2,2
   .word 2,2,2,2,2,2,2,2,2,2,2,2,
   .word 2,2,2,2,2,2,2,0,2,2,2,2,2
   .word 2,2,2,2,2,2,2,2,2,2,2,2,0

即使数组不全是 2,它仍然退出。

最佳答案

为此,您需要从访问每个数组的第一个元素开始,然后循环直到您的指针(或内存地址)超出数组范围。数组的地址也是第一个元素的地址(偏移量为 0 位),最后一个元素的偏移量为 48 位。

令 $t0 为当前元素的地址,$t1 为越界。

la    $t0, array
addiu $t1, $t0, 52  # 52 is outside the array
L1: 
beq   $t0, t1, L2
# do something here
addiu  $t0, $t0, 4
j     L1
L2:
# this part of the code happens after you traverse through an array.

此外,您可以使用 addi 代替 addiu,但正如您可能会在本类(class)后面学到的那样,addi 可能会导致异常。

关于arrays - 使用while循环遍历数组? - MIPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5967496/

相关文章:

c - 操作系统 X : write syscall is not executed when loading binary to memory

assembly - 错误 : Operation size not specified - NASm

c - 在数组中打印 'box'

java - 使用线程循环数组

javascript - for循环每5次迭代递增变量?

c - 这个函数的复杂度/BIG O是什么 "loops"

一行打印循环控制台的Javascript

java - 需要帮助解释该程序的结果

java - 初始化一副牌时如何使用toString方法

class - 从 x86-64 可执行文件中查找类和函数名称