MIPS汇编数组赋值陷入无限循环问题求助
Hey there! Let's break down what's going wrong with your MIPS code and fix that annoying infinite loop.
核心问题推测
From what you described—your code works fine when you remove the addiu related to $s2, but breaks when you keep it to store $t1 into percentage_Array—the issue almost certainly ties to incorrect pointer management or accidentally overwriting a loop control register with that addiu instruction.
关键排查点
Here are the most likely fixes to try:
You didn't reset
$s1to the start ofarraybefore the loop
After finishing input,$s1points to the empty slot right after your last entered number (or the 0 you used to stop reading). If you jump straight into processing without resetting$s1to the array's start, you'll read garbage values or 0s from memory, which can make your loop condition never fail. Fix this by addingla $s1, arrayright before your loop starts.Your
addiuinstruction for$s2is modifying the wrong register
It's easy to mistype register names! For example, if you meant to writeaddiu $s2, $s2, 4to shift thepercentage_Arraypointer, but accidentally wroteaddiu $t0, $s2, 4(where$t0is your loop counter), you'll overwrite the counter every iteration. This makes your loop condition (likebne $t0, $zero, loop) always true, trapping you in an infinite loop. Double-check that youraddiutargets$s2and not any loop-control registers.Loop termination logic is flawed
If your loop is supposed to run exactly 8 times (for 8 integers), make sure you initialize a counter (like$t0) to 8, decrement it each iteration, and stop when it hits 0. If you're using array values to control the loop (e.g., stop on 0), remember to exclude the final 0 you used to end input from processing.
修正后的代码示例
Here's a corrected version of your code with these fixes applied:
.data array: .space 32 # 8 integers × 4 bytes = 32 bytes percentage_Array: .space 32 newLine: .asciiz "\n" .text main: la $s1, array la $s2, percentage_Array # Read input until 0 is entered read_numbers: li $v0, 5 syscall beq $v0, $zero, end_read # Exit read loop if input is 0 sw $v0, 0($s1) addiu $s1, $s1, 4 # Move array pointer to next slot j read_numbers end_read: la $s1, array # Reset array pointer to start li $t0, 8 # Initialize loop counter for 8 elements loop: lw $t1, 0($s1) # Read element from array # Add your percentage calculation logic here (store result in $t1) sw $t1, 0($s2) # Save result to percentage_Array addiu $s2, $s2, 4 # Move percentage array pointer forward addiu $s1, $s1, 4 # Move array pointer forward addiu $t0, $t0, -1 # Decrement loop counter bne $t0, $zero, loop # Repeat until counter hits 0 # Exit program li $v0, 10 syscall
最后提示
Walk through your code step by step with these checks: confirm pointer positions, verify register names in your addiu instruction, and make sure your loop counter behaves as expected. That should squash the infinite loop while keeping your array storage functionality intact.
内容的提问来源于stack exchange,提问作者Argetim Ramadani

