2016-07-06 71 views
0

我想在ARM程序中用scanf读取多个值(一次一个)。我设法让scanf部分工作,它显然保存了正确的值。但是当我想要检索它们时,我只能得到最后一个数字,而其他数字会得到其他的东西。ARM汇编:由scanf存储的值未正确保存。

这是它给我:

Enter a number: 1 
Enter a number: 2 
You entered: 2129322344 and 2. 

应该说You entered 1 and 2.

我的代码如下所示:

.global main 
    .func main 

main: 
    PUSH {LR} 
    LDR R0, =entryMessage 
    BL printf 
    SUB SP, SP, #8 
    LDR R0, =scanformat 
    MOV R1, SP 
    BL scanf  @ Number is saved in SP - 8 
    LDR R0, =entryMessage 
    BL printf 
    ADD SP, SP, #4 
    LDR R0, =scanformat 
    MOV R1, SP 
    BL scanf  @ Number is saved in SP - 4 
    ADD SP, SP, #4 @ Restore SP to original 
    SUB SP, SP, #8 @ Prepare to read SP - 8 for first number 
    LDR R1, [SP] @ Read first number 
    ADD SP, SP, #4 @ Prepare to read SP - 4 for second number 
    LDR R2, [SP] @ Read second number 
    ADD SP, SP, #4 @ Restore SP to original 
    LDR R0, =printMessage 
    BL printf 
    POP {PC} 

_exit: 
    BX LR 

.data 
    entryMessage: .asciz "Enter a number: " 
    scanformat: .asciz "%d" 
    printMessage: .asciz "You entered: %d and %d.\n" 

谁能告诉我,为什么是它只有最后一个值被正确读取?

回答

2

ADD SP, SP, #4第二次致电scanf之前,那么该呼叫会覆盖前面输入的值。在装入R1R2之前,可以按相反顺序存储它们。所以堆栈指针永远不会高于你想要使用的存储值。

main: 
    PUSH {LR} 
    LDR R0, =entryMessage 
    BL printf 

    SUB SP, SP, #4 @ Reserve space for the first number entry 
    LDR R0, =scanformat 
    MOV R1, SP 
    BL scanf  @ Number is saved at original SP - 4 

    LDR R0, =entryMessage 
    BL printf 

    SUB SP, SP, #4 @ Reserve space for the second number entry 
    LDR R0, =scanformat 
    MOV R1, SP 
    BL scanf  @ Number is saved at original SP - 8 

    LDR R2, [SP] @ Read second number 
    ADD SP, SP, #4 @ Prepare to read first number 
    LDR R1, [SP] @ Read first number 
    ADD SP, SP, #4 @ Restore SP to original 
    LDR R0, =printMessage 
    BL printf 

    POP {PC}