Strncpy in MIPS has a weird behavior

 ̄綄美尐妖づ 提交于 2019-12-12 00:22:12

问题


Here's my code for strncpy. In theory it should work, but when I run tests on it it gives out garbage.

Arguments:
  $a0 = pointer to destination array
  $a1 = source string
  $a2 = number of characters to copy

Returns: the destination array

 strncpy:   
        beqz $a2, out
        lb $t0, 0($a1)      #load byte
        beqz $t0 out 
        subiu $a2, $a2, 1
        sb $t0, 0($a0)
        addiu $a0, $a0, 1
        addiu $a1, $a1, 1
        j strncpy
out:
    lb $0 0($a0)
        move $v0 $a0
        jr $ra

回答1:


coppy original address of destination array ($a0) and load it in "out:" in $a0->$v0. (in your version you would always get the char behind the last insert... in addition to the above mentioned problem in out:)

addi $a3 $a0 0

strncpy:
(...)

out:
move $a0 $a3
move $v0 $a0


来源:https://stackoverflow.com/questions/33021210/strncpy-in-mips-has-a-weird-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!