在MIPS中创建(和访问)一个数组

15

我尝试在MIPS Assembly中创建一个数组,然后将所有元素相加。但是,当我尝试汇编以下代码时,它会显示:

Error in read_array line 1 position 7: ".word" directive cannot appear in text segment Assemble: operation completed with errors.

这是我的汇编代码:

list: .word 3, 2, 1, 0, 1, 2
li $t0, 0x00000000  #initialize a loop counter to $t0
li $t4, 0x00000005  #last index of array
li $t3, 0x00000000  #this will hold our final sum
la $t1, list  #the address of list[0] is in $t1

loop: addi $t0, $t0, 0x00000001 #index++
  add $t5, $t0, $t0 #array index X2
  add $t5, $t0, $t0 #array index X2 again
  add $t6, $t5, $t1 #4x array index in $t6

  lw $t2, 0($t6)   #load list[index] into $t2
  add $t3, $t3, $t2 #$t3 = $t3 + $t2
  beq $t0, $t4, end
  j loop

end:
感谢!

我意识到这段代码中存在一些逻辑错误,但我的问题已得到解答。谢谢! - hodgesmr
这真的很奇怪,我不知道这个限制是否是有意为之,以保护初学者免于在执行数据时将其与代码混合而导致程序崩溃。在大多数汇编器中,您可以在任何位置使用.byte / .worddb / dd来发出您想要的任何字节。(例如,为某种原因发出指令的非默认编码。) - Peter Cordes
2个回答

14

你需要加入这行代码:

list: .word 3, 2, 1, 0, 1, 2

将代码放入.data部分。请参阅此快速教程


“快速教程”链接失效了。 - user7075574

6
错误提示告诉您不能将数据(.word 3, 2)放在代码段中。“Text segment”是一个旧式术语,意思是“代码段”http://en.wikipedia.org/wiki/Code_segment
汇编器希望您声明一个数据段并将数组放在那里。我从未使用过Mips汇编器,但我期望它应该是这样的。
.data
list: .word 3, 2, 1, 0, 1, 2

.text
start:
li $t0, 0x00000000  #initialize a loop counter to $t0
li $t4, 0x00000005  #last index of array
li $t3, 0x00000000  #this will hold our final sum
la $t1, list  #the address o

在我使用过的大多数汇编器中,它应该是 .text 而不是 .code - Carl Norum
@Carl:你可能是对的,特别是考虑到错误信息。我会进行更改。 - John Knoeller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接