user3244476
user3244476

Reputation: 21

Assembly language Array traversal

I'm new to assembly language and I'm having trouble with some basic programming problems and I was wondering if you guys could point me in the right direction. I'm trying to write a function that traverses through an array and sums up the values of its elements. Given given a pointer int *array and some length x.

What I've been able to do so far is write the initial data and place the initial pointer which isn't much but its a start. How would I use a loop in assembly to traverse through the array?

PUSH EBX
PUSH ECX
PUSH EDX
PUSH ESI
PUSH EDI

MOV EBX, array
MOV ECX, x

mov eax, 2;
mov ebx, array;
lea edx, [ebx+eax*4];

Upvotes: 0

Views: 2361

Answers (1)

Gunner
Gunner

Reputation: 5874

You do not need to save all of those registers. If your function uses esi, edi, ebx, ebp, then you must save them in the prologue and restore them in the epilogue. MASM can do that for you with the keyword uses

SomeProcedure proc uses esi, edi, ebx Val1:DWORD, Val2:DWORD

    ret
SomeProcedure endp

Here is one way you can do it:

.686                                     
.model flat, stdcall     
option casemap :none   

include kernel32.inc
includelib kernel32.lib

.data
Array   dd  1, 2, 3, 4, 5, 6, 7, 8, 9
Array_Size  equ ($ - Array) / 4

.code
start:

    push    Array_Size - 1
    push    offset Array
    call    SumArray
    ; eax contains sum of array
    ; print it out here.

    push    0
    call    ExitProcess

SumArray:    
    push    esi             ; need to preserve esi

    mov     esi, [esp + 8]  ; address of array
    mov     ecx, [esp + 12] ; size of array - 1
    xor     eax, eax        ; holds sum
    xor     edx, edx        ; index

AddIt:
    add     eax, [esi + edx * 4]     
    inc     edx
    dec     ecx
    jns     AddIt           ; is ecx ! neg repeat loop

    pop     esi
    ret
end start

Upvotes: 2

Related Questions