gpt4 book ai didi

string - 在 MIPS 程序集中反转字符串

转载 作者:行者123 更新时间:2023-12-04 18:49:41 24 4
gpt4 key购买 nike

我试图提示用户输入字符串的长度,为该字符串分配空间,然后反向打印出来。

对于我的生活,我无法弄清楚为什么这不起作用..

Sample Output:
(spim) run
Please enter an integer:
7
string
(spim)

现在“字符串”的长度应该是 6 吧? + 应为 7 的空终止字符。有人能发现我的方法哪里出了问题吗?
.data
nl: .asciiz "\n"
inputPrompt: .asciiz "Please enter an integer:\n"

theString: .space 32
theInteger: .word 1

.text
main:
la $a0, inputPrompt #load address a0 with prompt
li $v0, 4 #load system call, print string into v0
syscall

li $v0, 5 #load system call, read int into v0
syscall
sw $v0, theInteger #store saved int into $t0

li $v0, 8 #load system call, read string with mem address
la $a0, theString #load address of reserved string space
lw $a1, theInteger #load address of saved int length for string
syscall

lw $t0, theInteger
add $a1,$zero,$t0 #pass lenght of string
jal stringreverse #reverse the string

stringreverse:
add $t0,$a0,$zero #starting address
add $t1,$zero,$zero #i = 0
addi $t2,$a1,-1 #j = length-1

loop:
add $t3,$t0,$t1
lb $t4,0($t3) #the lb string[i]
add $t5,$t0,$t2
lb $t6,0($t5) #the lb string[j]
sb $t4,0($t5) #string[j] = string[i]
sb $t6,0($t3) #string[i] = string[j]
addi $t1,$t1,1 #i++
addi $t2,$t2,-1 #j--

slt $t6,$t2,$t1
beqz $t6,loop

exit:
li $v1, 4 #system call to print reversed string
la $a2, 0($a1)
syscall

li $v0, 10
syscall # Exit program

最佳答案

索引中有一个小错误……我没有在旧的基础上重写,而是使用了称为反向的新内存空间……

stringreverse:
add $t0,$a0,$zero #starting address
add $t1,$zero,$zero
add $t3,$zero,$zero #i = 0
addi $t2,$a1,-2 #j = length-1

loop:
add $t5,$t0,$t2
lb $t6,0($t5) #the lb string[j]
sb $t6,reverse($t3)
addi $t2,$t2,-1 #j--
addi $t3,$t3,+1 #i++

slt $t7,$t2,$t1
beqz $t7,loop

关于string - 在 MIPS 程序集中反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8198205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com