gpt4 book ai didi

assembly - 如何在循环中访问数组的各个元素?

转载 作者:行者123 更新时间:2023-12-05 08:43:18 24 4
gpt4 key购买 nike

我需要打印一个数组的单元格,我有一个包含单词“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

有没有办法使用指令 lb $a0, $s0($t0) 和一个我可以随时递增的寄存器?而不仅仅是一个数字?

最佳答案

要访问 array 的任何单个元素,您可以将其用作:

la $t3, array         # put address of array into $t3

如果数组是一个字节数组,比如:

array:   .byte    'H','E','L','L','O'

访问第 i 元素:

lb $a0, i($t3)        # this load the byte at address that is (i+$t3)

因为每个元素都是 1 个字节,所以要访问第 ith 个字节,访问 i 偏移 array 地址的地址.

您也可以通过以下方式访问它:

addi $t1,$t3,i
lb $a0,0($t1)

如果数组是单词数组,比如:

array:   .word    1,2,3,4,5,6,7,8,9

访问第 i 元素:

lw $a0, j($t3)        #j=4*i, you will have to write j manually

因为每个元素都是 4 字节并且要访问第 i 元素,您必须从 array< 的起始地址移动 i*4 字节.

还有一些其他的访问方式:

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)

示例 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

例子:打印字节数组:

    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

关于assembly - 如何在循环中访问数组的各个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868639/

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