如何访问.word数据“源”,递增到每个数字,分配给“目的地”?

时间:2019-04-13 09:17:52

标签: assembly mips mars-simulator

尝试访问和遍历“源”中的每个数字,直到我找到0,然后将这些数字保存到相同的“目标”索引中。

已尝试:很多东西,无法正确访问.word数据。不确定为什么。

.data
source:     .word   3, 1, 4, 1, 5, 9, 0
dest:       .word   0, 0, 0, 0, 0, 0, 0
countmsg:   .asciiz " values copied. "

.text

main:   add $s0,    $0,     $ra # Save our return address
    la  $t0,    source
    la  $t1,    dest


loop:   lw  $t3,    ($t0)       # read next word from source
    beq $t3,    $zero,  loopend # loopend if word is 0
    addi    $t4,    $t4,1       # increment count words copied
    sw  $t3,    0($t1)      # write to destination
    addi    $t0,    $t0,1       # advance pointer to next source
    addi    $t1,    $t1,1       # advance pointer to next dest
    j loop
loopend:

    move    $a0,    $v0     # We want to print the count
    li  $v0,    1
    syscall             # Print it
    la  $a0,    countmsg    # We want to print the count msg
    li  $v0,    4
    syscall             # Print it
    li  $a0,    0x0A        # We want to print '\n'
    li  $v0,    11
    syscall             # Print it
    jr  $s0         # Return from main. $ra in $s0

未在单词边界上对齐,不确定如何使迭代对齐

1 个答案:

答案 0 :(得分:0)

问题在于递增数组指针的方式。 word的宽度为4个字节,访问下一个元素需要向地址添加4。这无疑可以解释为什么您的访问权限未对齐。

还有其他两个问题。

main是一个特殊功能,您不应从main返回,而应调用exit()(syscall 10

单词计数在$t4中,并且打印不正确。

我还修改了您的循环,以在其中具有唯一的分支并抑制最后的跳转。最好总是在循环结束时进行测试。

这是更正的版本:

.data
source:     .word   3, 1, 4, 1, 5, 9, 0
dest:       .word   0, 0, 0, 0, 0, 0, 0
countmsg:   .asciiz " values copied. "

.text

main:   ### main is a special function. Should not save $ra
            #### $ra add $s0,    $0,     $ra # Save our return address
    la  $t0,    source
    la  $t1,    dest

loop:    lw  $t3,    ($t0)   # read next word from source
    addi $t4,    $t4,1       # increment count words copied
    sw   $t3,    0($t1)      # write to destination
    addi $t0,    $t0,4       # advance pointer to next source
        ### increment must be sizeof(word), ie 4
    addi $t1,    $t1,4       # advance pointer to next dest
    bne  $t3,$zero, loopend # loopend while word is != 0
        ### no longer required    j loop
loopend:

    move $a0,    $t4    # We want to print the count
                            # which is in $t4    
    li  $v0,    1
    syscall             # Print it
    la  $a0,    countmsg    # We want to print the count msg
    li  $v0,    4
    syscall             # Print it
    li  $a0,    0x0A        # We want to print '\n'
    li  $v0,    11
    syscall             # Print it
    li  $a0,    0       # EXIT_SUCCESS
    li  $v0,    10
    syscall             # exit
##    jr  $s0         # NO Return from main. use exit syscall