LC-3技术问询:如何将字符串存入非R0寄存器并正常打印?
Great question! Let's break down why your code isn't working and fix it right away.
The Root Cause: LC-3 Trap Instruction Rules
The TRAP x22 (PUTS) trap in LC-3 has a strict requirement: it always reads the starting address of the string to print from register R0. Your original code loads the string address into R3, but PUTS doesn't look at R3 at all—it checks R0, which contains random garbage values when your program starts. That's why you only see the halting message instead of your string.
Fixed Code
Here's how to adjust your code to keep the string address in R3 and still print correctly:
.ORIG x3000 LEA R3, L1 ; Load string address into R3 (this part is totally fine!) ADD R0, R3, #0 ; Critical step: Copy R3's value into R0 (PUTS needs R0) L1 .STRINGZ "Hello World" TRAP x22 ; Now PUTS reads the correct address from R0 and prints TRAP x25 .END
Bonus: Preserving R0's Original Value
If you need to keep whatever was originally in R0 (for other parts of your program), you can save it to memory first, then restore it after printing:
.ORIG x3000 ST R0, SAVE_R0 ; Save R0's initial value to a memory location LEA R3, L1 ADD R0, R3, #0 L1 .STRINGZ "Hello World" TRAP x22 LD R0, SAVE_R0 ; Restore R0 to its original value TRAP x25 SAVE_R0 .BLKW 1 ; Reserve 1 word of memory to hold R0's saved value .END
Key Takeaway
All LC-3 trap instructions have fixed register conventions:
PUTS(x22): Uses R0 for the string addressOUT(x21): Uses R0 for the character to printGETC(x20): Stores input character in R0PUTSP(x23): Uses R0 for the string address (for printing with spaces)
Always follow these conventions, and your traps will work as expected!
内容的提问来源于stack exchange,提问作者Hexedecimal

