Поиск массива с помощью Assembly 8086

Я пытаюсь сделать задание для класса, и я довольно застрял здесь. Что мне нужно сделать, так это найти в массиве двойных слов указанное значение двойного слова. Вот что у меня есть сейчас:

; DriverSub assembly language program: SUB adds two numbers pushed by Driver and displays SUM
; Author:  Daniel Strien
; Using Code from: RSzabo
; Date:    3/29/2012



.386
.MODEL FLAT

ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD



INCLUDE io.h            ; header file for input/output

cr      EQU     0dh     ; carriage return character
Lf      EQU     0ah     ; line feed


.STACK  4096            ; reserve 4096-byte stack


.DATA                   ; reserve storage for data

number12 DWORD   ?
array   DWORD 5 DUP (?)
prompt1 BYTE    "Enter first number:  ", 0
prompt2 BYTE    "Enter another number:  ", 0
prompt3 BYTE    "Enter a number to search for: ", 0
string  BYTE    13 DUP (?)

label1  BYTE    cr, Lf, "The value was found at Position (0 if not found): "    
pos     BYTE    16 DUP (?)

        BYTE    cr, Lf, 0




.CODE                           ; start of main program code

_start:

lea ebx, array      ; get address of array

    output  prompt1         ; prompt for first number
    input   string,13      ; read ASCII characters
    atod    string          ; convert to integer
    mov [ebx], eax     ;move the input to the array

output  prompt2         ; repeat for second number
    input   string, 13
    atod    string
    mov [ebx], eax     ;move the input to the array

output  prompt2         ; repeat for third number
    input   string, 13
    atod    string
    mov [ebx], eax     ;move the input to the array

output  prompt2         ; repeat for fourth number
    input   string, 13
    atod    string
    mov [ebx], eax     ;move the input to the array

output  prompt2         ; repeat for fifth(last) number
    input   string, 13
    atod    string
    mov [ebx], eax     ;move the input to the array

push ebx ;pushing the array adress to the stack

output prompt3      ; get search number
input string, 13
atod    string
push eax


    lea eax, number12
    push eax
    call search

    dtoa    pos, number12        ; convert to ASCII characters
    output  label1          ; output label and position

    INVOKE  ExitProcess, 0  ; exit with return code 0


PUBLIC _start                   ; make entry point public



search        PROC NEAR32  ; add two words passed on the stack
                     ; return the sum in the EAX register
        push   ebp               ; save EBP
        mov    ebp,esp           ; establish stack frame

;move search value to eax
mov eax, [ebp+12]


        ;compare values to the user input
    mov ebx, [ebp+16]       ; move array adress to EBX
    mov ecx, [ebx]      ;move first element to ECX
    cmp ecx, eax        ;comparing search number to the first value in the array
    je first                ;If equal return the position.

    mov ecx, [ebx+4]        ;move first element to ECX
    cmp ecx, eax        ;comparing search number to the second value in the array
    je second           ;If equal return the position.

    mov ecx, [ebx+8]
    cmp ecx, eax    ;comparing search number to the third value in the array
    je third                ;If equal return the position.

    mov ecx, [ebx+12]
    cmp ecx, eax        ;comparing search number to the fourth value in the array
    je fourth               ;If equal return the position.

    mov ecx, [ebx+16]
    cmp ecx, eax        ;comparing search number to the fifth value in the array
    je fifth                ;If equal return the position.
    jmp none

first:                  ;returns position 1
    mov eax, 1      
    jmp done

second:             ;returns position 2
    mov eax, 2
    jmp done

third:                  ;returns position 3
    mov eax, 3
    jmp done

fourth:             ;returns position 4
    mov eax, 4
    jmp done

fifth:                  ;returns position 5
    mov eax, 5
    jmp done

none:                   ;returns 0 if the search value is not found.
    mov eax, 0
    jmp done

done:
    mov ebx,[ebp+8]
    mov [ebp],eax

        pop    ebp               ; restore EBP
        ret 12                   ; return

search        ENDP
END                             ; end of source code

Проблема, с которой я сталкиваюсь, заключается в том, что программа будет выполнять все, но все равно будет возвращать 0, даже если значение существует в массиве. Кто-нибудь может понять, что я делаю неправильно?

заранее спасибо


person user1304088    schedule 30.03.2012    source источник
comment
В секции _start, после всех этих mov [ebx], eax, вы не увеличиваете ebx, поэтому все входные данные помещаете в первое dword (само по себе это не проблема, так как вы зарезервировали для него 5 DWORD). Это догадка, но вполне возможно, что вы портите свой стек вместе с адресом RET. array является константой, не проталкивайте/извлекайте его адрес в стек и обратно, используйте его адрес напрямую везде (исключая одну возможную ошибку, вы можете добавить его позже) и попробуйте передать свои параметры в search через регистры (я видел 2 параметра).   -  person karatedog    schedule 31.03.2012
comment
Спасибо, каратэдог. Я считаю, что проблема заключалась в том, что я не увеличивал массив в процедуре.   -  person user1304088    schedule 31.03.2012


Ответы (1)


lea ebx, array      ; get address of array

output  prompt1         ; prompt for first number
input   string,13      ; read ASCII characters
atod    string          ; convert to integer
mov [ebx], eax     ;move the input to the array

output  prompt2         ; repeat for second number
input   string, 13
atod    string
mov [ebx], eax     ;move the input to the array

....

Кажется, вы вообще не увеличивали ebx. Когда вы забыли увеличивать ebx на 4 каждый раз, когда вводили другое значение в матрицу, вы несколько раз переопределяли значение [ebx] при вводе. Итак, ваша матрица, начинающаяся с адреса ebx, будет иметь внутри только одно значение. Это значение пятого входного числа!

Ваше сравнение хорошее. Проблема не в нем. В любом случае, я предлагаю вам вместо этого попробовать использовать итерацию! Экономьте время и уменьшайте количество ошибок программирования! Вы можете использовать, например, edx (dl всего 8 бит) в качестве счетчика, поскольку других целей в этой программе у него нет!

person AsamRegnat    schedule 07.04.2012