我试图在给定大小和字符串时反转一串整数。这是我到目前为止所拥有的。我知道我的问题出现在循环部分,主要是弄清楚如何获得指向字符串后面的指针并将包含的内容移动到应该去的位置
任何帮助将不胜感激:
.data
Size: .word 9 # Size is 9
Vals: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # Vals[9]={1,2,..}
.text
main:
la $t1, Size # get the address of variable Size
la $t2, Vals # get the address of variable Vals
lw $t3, 0($t1) # fetch the value of Size to register $t3
sra $t4, $t3, 1 # right shift arithematic, now $t4 contains Size/2
sll $t3, $t3, 2 # left shift logic, now $t3 contains Size*4
loop:
lb $t5, 0($t2)
sb $t0, 36($t2)
sb $t0, ($t5)
addi $t0, $t0, 4
addi $t5, $t5, -4
bne $t5, $t4, end
j loop
end:
la $t0, Vals # get the address of Vals to $t0
la $t1, Size # get the address of Size to $t1
lw $t3, 0($t1) # get Size to $t3
sll $t3, $t3, 2 # left shift logic, now $t3 contains Size*4
add $t1, $t0, $t3 # $t1=Vals+Size*4 => array bound
li $v0, 1 # service 1 is print integer
lab4:
lw $a0, 0($t0) # load desired value into argument register $a0
syscall # print the value in $a0
addi $t0, $t0, 4 # increase array index
bne $t0, $t1, lab4 # check if reach array bound
答案 0 :(得分:1)
该循环中存在一些问题:
lw
/ sw
代替lb
/ sb
你应该做的是使用2个指针:一个指向数组的开头,另一个指向数组的末尾,然后读取两个项目并交换其内容。现在移动每个指针中的下一个元素(一个指针向前移动而另一个向后移动),并重复该过程直到处理完所有项目(即两个指针交叉时)。
E.g(剪辑):
addu $t7, $t2, $t3 # $t5 contains address of end of string
loop:
addi $t7, $t7, -4 # moves pointer backwards
lw $t5, 0($t2)
lw $t0, 0($t7)
sw $t5, ($t7) # interchange
sw $t0, ($t2) # contents
addi $t2, $t2, 4 # moves pointer forward
ble $t2, $t7, loop