【问题标题】:looping through array using while loop? - MIPS [duplicate]使用while循环遍历数组? - MIPS [重复]
【发布时间】:2011-08-23 11:23:57
【问题描述】:

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

.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,它仍然会退出。

【问题讨论】:

    标签: arrays loops assembly mips


    【解决方案1】:

    为此,您首先要访问每个数组的第一个元素,然后循环直到您的指针(或内存地址)超出数组范围。数组的地址也是第一个元素的地址(偏移量为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,但您可能会在课程后面了解到,addi 可能会导致异常。

    【讨论】:

    • 指针递增直到p == endp 是好的,但您可以在底部使用bne $t0, $t1, L1,而不需要beq j在同一个循环中。
    猜你喜欢
    • 1970-01-01
    • 2019-08-13
    • 2011-10-30
    • 2013-02-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多