string length for mips assembly

青春壹個敷衍的年華 提交于 2019-12-30 10:46:08

问题


Whenever I run the following code:

#counts length of a string

.data
 .data
string: .asciiz "Hello"

printedMessage: .asciiz "The length of the string: "

    .text
main:
  la $a0, string             # Load address of string.
        jal strlen              # Call strlen procedure.
        jal print
        addi $a1, $a0, 0        # Move address of string to $a1
        addi $v1, $v0, 0        # Move length of string to $v1
        addi $v0, $0, 11        # System call code for message.
        la $a0, printedMessage            # Address of message.
        syscall
        addi $v0, $0, 10        # System call code for exit.
        syscall


strlen:
li $t0, 0 # initialize the count to zero
loop:
lb $t1, 0($a0) # load the next character into t1
beqz $t1, exit # check for the null character
addi $a0, $a0, 1 # increment the string pointer
addi $t0, $t0, 1 # increment the count
j loop # return to the top of the loop
exit:
jr $ra

print:
li $v0, 4
  la $a0, printedMessage
  syscall

  li $v0, 1
  move $a0, $t1
  syscall


jr $ra

The QtSpim console prints "The length of the string: 0-". I've played around a bit with my print method, but I'm not sure what the problem is. So, the question: How do I fix my print outs? I should be printing out the info in $t0 since it's the counter.

Thanks in advance!


回答1:


Not entirely sure what you mean by fix print out, but one problem is that your count register in the strlen function is $t0 while your second syscall in print: is called with argument $t1

Changing that $t1 to $t0 and running it gives output 5.



来源:https://stackoverflow.com/questions/20513857/string-length-for-mips-assembly

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