MIPS - 帮助初始化数组

问题描述 投票:0回答:1

我试图将内存数组初始化为值1,2,3 .. 10.虽然我遇到了一些麻烦。到目前为止,这是我的工作:

.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  

任何帮助将非常感激。

arrays assembly mips
1个回答
1
投票

您的代码有几个问题。

  1. 如果你使用sw(存储字),你假设一个“字”数组。它的大小应该是4 * 10。如果你想要一个字节数组,请使用sb
  2. 你没有在$t3中增加数组指针
  3. $ 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  

正如@PeterCordes所建议的那样,这可以通过合并循环计数器和数组值寄存器来优化循环中的一条指令。 C中相应的循环将是

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

和相应的代码

.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  
© www.soinside.com 2019 - 2024. All rights reserved.