BlazerBrown
BlazerBrown

Reputation: 76

Iterating through an array in NASM assembly code

So I'm currently taking an assembly language class and we are trying to create and sort an array from input. I can get the sorting logic just fine, but I'm having a great deal of trouble trying to iterate through the array.

For further clarification of what the following code does, we are supposed to read in integers from the command line. The number 0 delimits the end of user input, and then the sorting method is called.

That works fine, it's the array iteration that is not working.

Here is a sample of what I'm doing

main:
        mov ebx, array  ;move the variable array to ebx
        mov ecx, 0          ;set ecx to zero
        jmp input            ;jump to input
input:
        mov edx, 0          ;move 0 to edx
        call ReadInt        ; read in an integer from input to eax
        cmp eax, edx     ; compare the integer to 0
        je sort                ;jump if it equals zero to the sort method
        mov [ebx+ecx], eax    ;moves eax to the ecxth element of the array stored in ebx
        add ecx, 1                    ;increment ecx by 1
        jmp input                        ; jump back to input

When I go to print the array in a later function, no matter what element I choose, it's always some crazy large number.

Is my logic off in the above code snippet? What improvements would you suggest?

Upvotes: 3

Views: 12690

Answers (1)

Jester
Jester

Reputation: 58822

You need to scale by 4 since asm uses byte indexing but each integer is 4 bytes. Thus, you need something like mov [ebx+ecx*4], eax. Alternatively, increment ecx by 4 in each iteration.

Upvotes: 3

Related Questions