Eric C.
Eric C.

Reputation: 31

MIPS Trying to Copy Array Using Stack

I have been trying to copy a word array in MIPS using stacks, and for some reason it's not working and I can't figure out why... help please, thank you! :)

     .data 
       array:    .word 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 
                 .word 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 
                 .word 41, 43, 45, 47, 49, 51, 53, 55, 57, 59
       length:   .word 30
       array2:   .space 120
       text:        .asciiz "\n\nArray 1 is: \n\n"
       text2:    .asciiz "\n\nArray 2 is: \n\n"

    .text
    .globl main
    main:
     la $t0, array
     li $t1, 0
     lw $t2, length
     la $t3, array2

    loopToPushOntoStack:
     lw $t4, ($t0)      #load first element of the array onto t4
     sub $sp, $sp, 4        #move stack pointer down by 4
     sw $t4, ($sp)      #store t4 onto stack
     add $t0, $t0, 4        #increment array pointer by 4
     add $t1, $t1, 1        #increment counter by 1
     blt $t1, $t2, loopToPushOntoStack

    Reset:
     la $t0, array
     li $t1, 0
     lw $t2, length

    loopToPopStack:
     lw $t4 ($sp)
     move $a0, $t4
     li $v0, 1
     syscall
     addu $sp, $sp, 4
     sw $t4, ($t0)
     sw $t4, ($t3)
     add $t0, $t0, 4
     add $t3, $t3, 4
     add $t1, $t1, 1
     blt $t1, $t2, loopToPopStack

    la $s3, text
    move $a0, $s3
    li $v0, 4
    syscall

    li $t1, 0

    printArrayOne:
      lw $s4, ($t0)
      move $a0, $s4
      li $v0, 1
      syscall
      add $t0, $t0, 4
      add $t1, $t1, 1
      blt $t1, $t2, printArrayOne

    la $s4, text2
    move $a0, $s4
    li $v0, 4
    syscall


    li $t1, 0

    printArrayTwo:
       lw $s5, ($t3)
       move $a0, $s5
       li $v0, 1
       syscall
       add $t3, $t3, 4
       add $t1, $t1, 1
       blt $t1, $t2, printArrayTwo

    exit: 
       li $v0, 10
       syscall

p.s. I think the problem occurs in the following function:

    loopToPopStack:
       lw $t4 ($sp)
       move $a0, $t4
       li $v0, 1
       syscall
       addu $sp, $sp, 4
       sw $t4, ($t0)
       sw $t4, ($t3)
       add $t0, $t0, 4
       add $t3, $t3, 4
       add $t1, $t1, 1
       blt $t1, $t2, loopToPopStack

but i can't figure out what's exactly wrong with it haha.

Upvotes: 0

Views: 1613

Answers (1)

Eric C.
Eric C.

Reputation: 31

Nevermind, fixed it! I needed to reset the $t0 to array, as well as $t3 to array 2 before I print them, or they are pointing at 120 bytes beyond the array's starting address.

Upvotes: 1

Related Questions