【问题标题】:MIPS - Help initializing arrayMIPS - 帮助初始化数组
【发布时间】:2019-04-01 18:08:56
【问题描述】:

我正在尝试将内存数组初始化为值 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. 如果您使用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  
    

    【讨论】:

    • 您可以使用数组元素值作为循环计数器,bne $t3, $t0, top。 (在循环外初始化t0 = 11。)
    • 对 C 的更直译是指针增量,因此没有 i-1
    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多