MIPS - 帮助初始化阵列



我正在尝试将内存数组初始化为值 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  

任何帮助将不胜感激。

您的代码存在几个问题。

  1. 如果使用sw(存储单词(,则假定为"word"数组。它的大小应该是4 * 10。如果您使用字节数组,请使用 sb .

  2. 您不会递增数组指针$t3

  3. $t 2 中的数组值存在相同的问题

.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  

最新更新