1

I am trying to initialize memory array to values 1, 2, 3.. 10. Though I am having a bit of trouble. Here is my work so far:

.data
myarray: .space 10
.text
la $t3, myarray  # Load the address of myarray 
addi $t2, $zero, 1  # Initialize the first data value in register.
addi $t0, $zero, 10  # Initialize loop counter $t0 to the value 10

top:

sw $t2, 0($t3)   # Copy data from register $t2 to address [ 0 +
# contents of register $t3]
    addi $t0, $t0, -1   # Decrement the loop counter
    bne $t0, $zero, top  

Any help would be much appreciated.

1 Answer 1

2

There are several problems with your code.

  1. If you use sw (store word), you assume a "word" array. Its size should be 4*10. If you wand a byte array, use sb .

  2. You do not increment the array pointer in $t3

  3. Same problem for the array values in $t2

.data
  myarray: .space 10
.text
    la $t3, myarray     # Load the address of myarray 
    addi $t2, $zero, 1  # Initialize the first data value in register.
    addi $t0, $zero, 10 # Initialize loop counter $t0 to the value 10
top:
    sb $t2, 0($t3)      # Copy data from register $t2 to address [ 0 +
                        # contents of register $t3]
    addi $t0, $t0,-1    # Decrement the loop counter
    addi $t3, $t3, 1    # next array element
    addi $t2, $t2, 1    # value of next array element
    bne $t0, $zero, top  

As suggested by @PeterCordes, this can be optimized by merging the loop counter and the array values register to suppressed one instruction in the loop. The corresponding loop in C will be

for(i=1, ptr=array; i!=11; ptr++,i++) *ptr=i;

And the corresponding code

.data
  myarray: .space 10
.text
    la $t3, myarray     # Load the address of myarray 
    addi $t2, $zero, 1  # Initialize the first data value in register.
    addi $t0, $zero, 11 # Break the loop when array value reaches 11 
top:
    sb $t2, 0($t3)      # Copy data from register $t2 to address [ 0 +
                        # contents of register $t3]
    addi $t2, $t2, 1    # Increment array value/loop counter
    addi $t3, $t3, 1    # next array element
    bne $t0, $t2, top  
Sign up to request clarification or add additional context in comments.

2 Comments

You can use the array-element value as a loop counter, with bne $t3, $t0, top. (initialize t0 = 11 outside the loop.)
A more literal translation to C would be a pointer increment, so there's no i-1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.