MIPS-帮助初始化阵列

时间:2019-04-01 18:08:57

标签: arrays assembly 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 个答案:

答案 0 :(得分:1)

您的代码有几个问题。

  1. 如果使用sw(存储字),则假定为“字”数组。它的大小应为4 * 10。如果要通过字节数组,请使用sb

  2. 您不增加$t3

  3. 中的数组指针
  4. $ 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