Home > Software design >  I have trouble using arrays in assembly / emu8086
I have trouble using arrays in assembly / emu8086

Time:04-04

I am a very beginner in assembly. I want to print 2 members of an array.
This is how I first wrote my code:

        mov PRIME_NUMBERS[1],2
        mov ax,PRIME_NUMBERS[1]
        call PRINT
        
        mov PRIME_NUMBERS[2],3
        mov ax,PRIME_NUMBERS[2]
        call PRINT

and it prints "23" and it's ok, but when I code like:

        mov PRIME_NUMBERS[1],2
        mov PRIME_NUMBERS[2],3
        mov ax,PRIME_NUMBERS[1]
        call PRINT
         
        mov ax,PRIME_NUMBERS[2]
        call PRINT

it prints "7703و". The element number 1 seems to have been replaced by the number 770. I can not find my mistake!

my code :

.MODEL SMALL
.STACK 100H
.DATA
max_num_check dw ?
current_num dw ?
prime_numbers dw 100 DUP (0)

.CODE

MAIN PROC

        ;define data segment 
        mov ax,@DATA
        mov DS,ax
        ;------------------
        
        mov PRIME_NUMBERS[1],2
        mov ax,PRIME_NUMBERS[1]
        call PRINT
        
        mov PRIME_NUMBERS[2],3
        mov ax,PRIME_NUMBERS[2]
        call PRINT
        
        HLT 
MAIN ENDP

; to print numbers , you should use mov ax,number and CALL PRINT
PRINT PROC  
         mov cx,0
         mov dx,0
         mov bx,10
         l1:
         cmp ax,0
         je l2
         
         div bx
         push dx
         inc cx
         xor dx,dx
         jmp l1
         
         l2:
         cmp cx,0
         je end
         pop dx
         add dx,'0'
         dec cx
         mov ah,2h
         int 21h
         jmp l2
         
         end:
         xor ax,ax
ret   
PRINT ENDP

MAX_NUM_TO_CHECK PROC 
    mov cx,0
    here:
    mov ax,cx
    mul cx
    cmp ax,current_num
    jge store
    inc cx
    jmp here
    
    store:
    mov max_num_check,cx
ret
MAX_NUM_TO_CHECK ENDP

END MAIN

CodePudding user response:

770 is 0302 in hex. Note that the value 3 appears in the upper byte.

The assembler does not scale the subscript by the size of the array member, so PRIME_NUMBERS[1] is PRIME_NUMBERS 1 instead of PRIME_NUMBERS 2, as you intended.

Each number occupies two bytes. It is storing the first number into the bytes PRIME_NUMBERS 1 and PRIME_NUMBERS 2. It is storing the second number into the bytes PRIME_NUMBERS 2 and PRIME_NUMBERS 3, overwriting the upper byte of the first number. Then when it tries to read the first number, it gets one byte of the first number and one byte of the second number squished into a single value.

(Actually what you probably intended is for the first number to be stored in PRIME_NUMBERS 0 and the second number to be stored in PRIME_NUMBERS 2.)

  • Related