Mips 2d阵列功能

时间:2014-04-07 17:00:48

标签: arrays algorithm function mips

我试图创建一个算法,找到n×n方阵的轨迹A. n-by-n方阵A的轨迹被定义为主对角线上元素的总和A.的主要思想是,在这个层面上,多维数组被存储为一维数组,并且多维索引存储(对于具有m行和n列)转换为一维索引。由于我不熟悉mips尝试将其集成到代码中,我的最新尝试不成功。

我已将寄存器设置为以下内容:

$ a0 =数组的基地址(矩阵),

$ a1 = n,行数和列数

$ v0 = trace

$ t0 = i

trace:   move $v0, $zero       
         move $t0, $zero       
         bne $t0,$a1,end      
         sll $t1,$a0,4
         add $t1,$t1,$t0
         sll $t1,$t1,2
         add $t2,$t1,$a0
         lw $t0,0($t1)
         addi $sp, $sp, 8
         sw $t1,0($t0)
         j trace
end:     jr $ra       

但无济于事,答案没有按照预期出来,算法的格式应该如下;

 trace = 0
 for i = 0 to n-1
   trace = trace + a[i,i]
 end for

1 个答案:

答案 0 :(得分:1)

我添加了一些表明可疑行为的评论

trace:   move $v0, $zero       
         move $t0, $zero       
loop:    bne $t0,$a1,end      
         sll $t1,$a0,4    ; t1 = a0 * 16, a0 is the base address, should probably be $t0
         add $t1,$t1,$t0  
         sll $t1,$t1,2
         add $t2,$t1,$a0
         lw $t0,0($t1)
         addi $sp, $sp, 8 ; What are you doing with $sp?  perhaps this should be add $v0,$v0,$t0
         sw $t1,0($t0)    ; What are you storing here?
         j trace          ; This should probably jump to loop, or the code will never end
end:     jr $ra 

另请注意,sll假定矩阵的大小为16。