Search code examples
assemblymipsmips32mars-simulatormips64

Save outputs directly after inputs in data segment


This is my code:

.data  
.ascii "r", "o", "r", "y", "\n"
key: .word 2
.text
.globl main

main:   la  $t0, string
        move    $t5, $t0         # preserve original data
        la  $t1, key            # load cypher into t1 reg
        lw  $a1, 0($t1)      # key loaded into a1 reg   

Loop:   lb  $a0, 0($t5)      # ith element of array loaded into a0    
        beq $a0, 10, exit_all   # if ith character is \n, get out of loop
        jal sub1               # otherwise, call sub  

        addi    $t5, $t5,      # increment index of array   
        j   Loop

exit_all: syscall 

sub1:   
    some code
    move $v0, $t0              # what i want to return to main
    jr  $ra                 # exit iteration

I have a loop with a sub-routine in it. The sub returns (in the $v0 reg) an output i want to save every time the 'jr $ra' command returns the flow to my main function. I need to save these outputs directly after my inputs in the data segment. How do i do this? If it was just one output, i could say:

sb $v0, 4($t1)

and it would be saved directly after. But there are multiple outputs, so how do i do this in a general way?


Solution

  • You need to reserve space in your data section for all of your output values, so for example for 32 output values add:

    results: .byte 32
    

    to your data section. Then set a register to the address of results, and increment the register each time around the loop:

            la  $t7, result
    ...
    Loop:   ...
            jal sub1
            sb  $v0,0($t7)
            addiu $t7,1
            j loop
    

    The above code is untested.