0

I have already done that, but I don't seem to understand the $sp - Stack pointer fully. As it says that the Stack Pointer $ sp should always point to the last occupied memory cell of the stack. (when I run it the $sp stays the same until the program prints then changes).

May someone please tell me what is going on with the $sp here? or what should be done exactly in order for it to execute correctly as asked for?

Here is my code:

.data
     arr: .space 20 #create array of length 5
     inputPrompt: .asciiz "Please enter a whole number: \n"
     spaceChar: .asciiz " "
     
.text
     main:
     #Prompt user to enter a whole number
     li $v0, 4
     la $a0, inputPrompt
     syscall
     
     jal while
     
     #print in reversed order
     addi $t0, $zero, 16
     jal whileOutput

   
        while:
            beq $t0, 20, exitWhile
            
            #read input
            li $v0, 5
            syscall
            
            addi $sp, $sp, -8 #make up space in stack
            sw $s0, 0($sp) 
            sw $ra, 4($sp)
            
            sw $v0, arr($t0)
            move $s0, $v0
            
            add $t0, $t0, 4
            j while
     
        exitWhile:
            jr $ra 
        
        
        
     whileOutput:
            beq $t0, -4, exitOutput

                lw $t6, arr($t0)
                
                #print Integer
                li $v0, 1
                move $a0, $t6
                syscall
        
                #print space
                li $v0, 4
                la $a0, spaceChar
                syscall
        
            addi $t0, $t0, -4
        
                j whileOutput
            
            
    exitOutput:
            #restore space in Stack
            lw $s0, 0($sp)
            lw $ra, 4($sp)
            addi $sp, $sp, 8
            
            #end program
            li $v0, 10
            syscall

     ```
     
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
S. Jilani
  • 1
  • 1
  • 1
    Suggest to write tiny programs to test the two or three capabilities you need to do this, then stitch them together. Use single step debugging to debugging each little capability, and also your stitching them together, as the control flow matters, and there are serious control flow problems in the code shown. – Erik Eidt Nov 17 '21 at 23:44
  • You've already allocated space, so why do you need `$sp`? – ggorlen Nov 23 '21 at 16:50

0 Answers0