我试图将内存数组初始化为值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
任何帮助将非常感激。
您的代码有几个问题。
sw
(存储字),你假设一个“字”数组。它的大小应该是4 * 10。如果你想要一个字节数组,请使用sb
。$t3
中增加数组指针.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