问题描述
我一直在尝试将一个字符串复制到另一个字符串,但找不到办法做到这一点有人可以帮忙吗? 这是问题: 编写一个程序,使用过程调用将字符串 S 复制到 T。假设字符串以空字符结尾。
这是某人在堆栈溢出中制作的代码,正如我的导师告诉我的那样很好,但只需将其修改为过程调用
.data
str1: .asciiz "My Name is Suliman." # Store initial string
str2: .space 128 # Allocate memory space for the new string
.text
main:
la $s0,str1 # Load address of first character
la $s1,str2 # Load the address of second string
loop:
lbu $t2,0($s0) # Load the first byte of $s0 (str1) into $t2
sb $t2,0($s1) # Save the value in $t2 at the same byte in $s1 (str2)
addi $s0,$s0,1 # Increment both memory locations by 1 byte
addi $s1,$s1,1
bne $t2,$zero,loop # Check if at the zero delimiter character,if so jump to
j done
done:
li $v0,4
la $a0,str2
syscall # Print the copied string to the console
li $v0,10 # Program end syscall
syscall
解决方法
我在这里也有一些评论来解释我在做什么,我只是用了 128 个字节来留出一些空间,我还打印了复制的字符串
.data
str1: .asciiz "My Name is Suliman." # Store initial string
str2: .space 128 # Allocate memory space for the new string
.text
main:
la $t0,str1 # Load address of first character
la $t1,str2 # Load the address of second string
loop: # do {
lbu $t2,0($t0) # Load the first byte of $t0 (str1) into $t2
sb $t2,0($t1) # Save the value in $t2 at the same byte in $t1 (str2)
addi $t0,$t0,1 # Increment both pointers by 1 byte
addi $t1,$t1,1
bne $t2,$zero,loop # }while(c != 0)
# j done # execution falls through to the next instruction by itself
#done:
li $v0,4
la $a0,str2
syscall # Print the copied string to the console
li $v0,10 # Program end syscall
syscall