无法将东西插入到程序集中的数组中

Trouble inserting things into an array in assembly

我目前正在尝试学习汇编,我的任务之一是获取用户输入的整数并将这些数字插入到数组中。一旦数组有 7 个整数,我将遍历数组并打印出数字。但是,我目前卡在如何将数字插入数组中。这是我现在拥有的代码:

.DATA

inputIntMessage BYTE "Enter an integer: ", 0
inputStringMessage BYTE "Enter a string: ", 0


intArray DWORD 0,0,0,0,0,0,0
intCounter DWORD 0
user_input DWORD ?

.CODE

main PROC

mov eax, intCounter
mov edx, 0

top: 
    cmp eax, 7      
    je final1
    jl L1

L1: intInput inputIntMessage, user_input
    mov ebx, user_input
    mov intArray[edx], ebx ;This is where I think the problem is.
    add edx, 4
    inc eax
    jmp top

final1:

mov ecx, 0
mov edx, 0
printarrayloop: 
            cmp edx,7
            jl L2
            je next
L2: intOutput intArray[ecx] 
    add ecx, 4
    inc edx
next:

next:直接进入下一题;与插入数组问题无关。我的想法是我应该使用数组的偏移量,这样我就可以访问数组中每个元素的地址并直接更改它,但我不知道如何。有人能指出我正确的方向吗?

编辑:当我 运行 程序 window 提示用户输入一个整数 7 次(这是预期的),然后打印出用户输入的第一个数字。但是,window 应该会打印出用户输入的所有数字。

您的代码只打印一个数字的主要原因是因为显示数字数组的代码是这样做的:

mov ecx, 0
mov edx, 0
printarrayloop: 
    cmp edx,7
    jl L2
    je next
L2: intOutput intArray[ecx] 
    add ecx, 4
    inc edx
next:

缺少的是在显示第一个数字后不继续循环。您需要跳回到 printarrayloop 来处理下一个数字。在 inc edx 下方添加:

     jmp printarrayloop

您可能还需要考虑一些其他事项。在这段代码中:

top: 
    cmp eax, 7      
    je final1
    jl L1

L1: intInput inputIntMessage, user_input
[snip]
final1:

你做到了 cmp eax, 7。如果相等则跳出。如果它小于那么你只是分支到标签 L1 无论如何。您可以通过删除无关的 jl L1 分支和标签来修改该代码。所以你会有这个:

top: 
    cmp eax, 7      
    je final1    
    intInput inputIntMessage, user_input

在此代码中有一些额外的指令可以删除:

mov ecx, 0
mov edx, 0
printarrayloop: 
    cmp edx,7
    jl L2
    je next
L2: intOutput intArray[ecx] 
    add ecx, 4
    inc edx
    jmp printarrayloop
next:

类似于我之前使用 cmp edx,7EDX 与 7 进行比较的评论。你可以简单地说,在比较它是否等于 7 之后,你跳出循环到 next 。如果小于 7,它将继续并打印出数字。所以您的代码可能如下所示:

mov ecx, 0
mov edx, 0
printarrayloop: 
    cmp edx,7
    je next
    intOutput intArray[ecx] 
    add ecx, 4
    inc edx
    jmp printarrayloop
next:

x86 32 位代码具有缩放寻址模式(带位移)。您可以找到此摘要中描述的所有寻址模式 here and more detailed description here

您可以在寻址时使用比例因子(将寄存器乘以 1、2、4 或 8)。您的代码如下所示:

    mov intArray[edx], ebx 
    add edx, 4

EDX指向你要显示的元素号,乘以4就占了一个DWORD[=58=的大小] 是 4 个字节。所以你可以删除 add edx, 4 并将访问数组的代码更改为:

    mov intArray[edx*4], ebx 

intArray[edx*4] 是一个等同于 intArray+(edx*4)

的地址

你可以在输出的时候做类似的改动。删除此行:

    add ecx, 4

并使用缩放寻址:

    intOutput intArray[ecx*4]