我需要打印一个数组的单元格,我有一个包含“HELLO_WORLD”这个词的数组,我设法自己打印了一个索引,但我无法一一打印所有单元格,这是代码:
loop:
la $t0, hexdigits # address of the first element
lb $a0, 5($t0) # hexdigits[10] (which is 'A')
li $v0, 11 #system call service
syscall
addi $a0, $a0, 2
li $v0, 11 # I will assume syscall 11 is printchar (most simulators support it)
syscall # issue a system call
j end
Run Code Online (Sandbox Code Playgroud)
无论如何,是否可以将指令 lb $a0, $s0($t0) 与我可以随时递增的寄存器一起使用?而不仅仅是一个数字?
要访问 的任何单个元素array,您可以将其用作:
la $t3, array # put address of array into $t3
Run Code Online (Sandbox Code Playgroud)
如果数组是字节数组,例如:
array: .byte 'H','E','L','L','O'
Run Code Online (Sandbox Code Playgroud)
访问第 i个元素:
lb $a0, i($t3) # this load the byte at address that is (i+$t3)
Run Code Online (Sandbox Code Playgroud)
因为每个元素都是 1 个字节,所以要访问第i个字节,访问与 的地址i偏移的地址array。
您还可以通过以下方式访问它:
addi $t1,$t3,i
lb $a0,0($t1)
Run Code Online (Sandbox Code Playgroud)
如果数组是一个单词数组,例如:
array: .word 1,2,3,4,5,6,7,8,9
Run Code Online (Sandbox Code Playgroud)
访问第 i个元素:
lw $a0, j($t3) #j=4*i, you will have to write j manually
Run Code Online (Sandbox Code Playgroud)
因为每个元素如果是 4 字节并且要访问第i个元素,则必须i*4从array.
还有一些其他的访问方式:
li $t2, i # put the index in $t2
add $t2, $t2, $t2 # double the index
add $t2, $t2, $t2 # double the index again (now 4x)
add $t1, $t3, $t2 # get address of ith location
lw $a0, 0($t1)
Run Code Online (Sandbox Code Playgroud)
示例 1:
.data
array: .byte 'H','E','L','L','O','_','W','O','R','L','D'
string: .asciiz "HELLO_WORLD"
size: .word 11
array1: .word 1,2,3,4,0,6,7,8,9
.text
.globl main
main:
li $v0, 11
la $a2,array
lb $a0,0($a2) #access 1st element of array or array[0]
syscall
lb $a0,1($a2) #access 2nd element of byte array or array[1]
syscall
lb $a0,2($a2) #access 3rd element of byte array or array[2]
syscall
lb $a0,10($a2) #access 11th element of byte array or array[10]
syscall
li $a0,10
syscall
syscall
li $v0,1
la $a3,array1
lw $a0,0($a3) #access 1st element of word array or array[0]
syscall
lw $a0,4($a3) #access 2nd element of word array or array[1]
syscall
lw $a0,8($a3) #access 3rd element of word array or array[2]
syscall
lw $a0,12($a3) #access 4th element of word array or array[3]
syscall
jr $ra
Run Code Online (Sandbox Code Playgroud)
示例:打印字节数组:
li $v0, 11
la $a2,array
lw $t0,size
loop1: #print array
lb $a0, 0($a2) #load byte at address stored in $a2
syscall
add $t0,$t0,-1
add $a2,$a2,1 #go to the next byte, since it is a byte array it will go to the address of next element
#to use it for printing word array instead of adding 1 add 4
bgtz $t0, loop1
Run Code Online (Sandbox Code Playgroud)