首页 > 解决方案 > 在递归函数中分配堆栈以计算字符串长度 MIPS

问题描述

我遇到了一个问题,即把分配部分放在计算字符串长度的函数中。这是我最近用外部分配部分计算字符串长度的工作。它工作正常,但要求说它需要在递归函数内。你对此有什么建议吗?谢谢!

.data
    string: .asciiz "Hi"
    result: .asciiz "\nThe length of your text: "
    userInput: .space 100
.text
main:
    #Display message
    la $a0, string
    li $v0, 4
    syscall
    
    #allocate
    la $a0, string
    move $t0, $a0
    addi $sp, $sp, -16
    sw $t0, 12($sp)
    sw $ra, 8($sp)

    #initialize counter
    li $v0, 0
    
    #call the function
    jal StrLen
    
    move $t0, $v0
    
    #display result
    li $v0, 4
    la $a0, result
    syscall
    
    #result
    move $a0, $t0
    li $v0, 1
    syscall
    
    li $v0, 10
    syscall
    
StrLen:
    lw $a0, 12($sp)#load the string
    lb $a1, 0($a0) #get a byte from string
    bne $a1, $0, Continue
    j return
Continue:
    addi $a0, $a0 ,1 #go to next byte
    addi $sp, $sp, -16
    sw $ra, 8($sp)  # store the return address in the stack
    sw $a0, 12($sp) # store new address in stack
    addi $v0, $v0, 1 #increase counter
    j StrLen # return to the top of the loop
return: 
    #deallocate stack
    lw $ra, 8($sp)
    addi $sp, $sp, 16
    jr $ra

标签: recursionstackmips

解决方案


推荐阅读