问题
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