2015-10-09 90 views
0

我正在寫MIPS的strncpy,但是我遇到了麻煩null-終止字符串。如果我不自己終止它,那麼字符串會一直亮着。我曾嘗試sb $__ 0($0)但似乎並沒有工作......在MIPS中終止一個字符串?

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

strncpy: 
    add $t1 $zero $zero #counter 
    beq $a2 $0 done # if num chars to copy is 0, return. 
    j cpyLoop 

cpyLoop:  

    beq $t1 $a2 done # if counter == num to copy, end 
    lb $t2 0($a1) # load the character 
    beq $t2 $0 done #if we reach the null char, end 
    sb $a0 0($a1) 
    addi $a0 $a0 1 #increment the pointer in dest array 
    addi $a1 $a1 1 #increment the pointer in source array 
    addi $t1 $t1 1 #increment the counter 
    j cpyLoop 



done: 
    lb $a0 0(0) 
    move $v0 $a0 
    jr $ra 
+0

這是同樣的問題http://stackoverflow.com/questions/33021210/strncpy-in-m ips-has-a-weird-behavior – Michael

+0

_「我已經嘗試過's $ __ 0($ 0)'」_。試圖寫入地址0很少是一個好主意。 – Michael

回答

0

,使這個職位完全我將外套的一部分從上述dublicate poast和完成它:

addi $a3 $a0 0 


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: 
     move $a0 $a3 
     move $v0 $a0 
     jr $ra