Page 1 of 1

## MASM - Arrays

### #1 GunnerInc

• "Hurry up and wait"

Reputation: 902
• Posts: 2,349
• Joined: 28-March 11

Posted 21 November 2011 - 07:07 PM

What is an array?
An array is a contiguous block of memory, nothing more and nothing less. Each array item is at its own address.

What is a Structure?
A Structure is an array on steroids, it is also a contiguous block of memory. Unions are a different beast, memory can overlap.

If you define the variable - szHello BYTE "Hello", 0 it will create an array of 6 bytes (including the null terminator)
Lets say szHello starts at address - 4206719 where will it end? It will end at address - 4206724

If dwHello starts at 4206719, how big is it in memory? Where would it end?

dwHello DWORD 72, 101, 108, 108, 111, 0
Spoiler

Once you understand that arrays are a contiguous block of memory, then it is easy to add to and read from an array.

Ok, how do you access each element?
This is one way...
```.code    mov     esi, offset szHello
xor     ecx, ecx
@@:
xor     eax, eax
mov     eax, [esi + 1 * ecx]
; ASCII code is in al, do something with it here
PrintDec al
inc     ecx
cmp     ecx, 6
jne     @B
```

Since we don't need the high bytes of eax, we will zero it out at line 4
line 5 - esi is the pointer to the array, 1 is the element size and ecx is the element index
line 6 - increase our element counter
line 7 - the length of our array, did we reach it?

Simple right? Same thing to access a dword array, except we change the element size to 4:
```    mov     esi, offset dwHello
xor     ecx, ecx
@@:
xor     eax, eax
mov     eax, [esi + 4 * ecx]
; ASCII code is in al, do something with it here
PrintDec al
inc     ecx
cmp     ecx, 6
jne     @B
```

If you were using an array of WORDS, the element size would be 2

How would I store numbers in an array then sum up the array?
This comes up a lot, so I will show you:
```.data?
dwArray      dword    4 dup (?) ; store 4 numbers

.code
mov     esi, offset dwArray
xor     ecx, ecx
mov     edx, 1
; store 1 - 5 in array
@@:
mov    [esi + 4 * ecx], edx
inc     edx
inc     ecx
cmp     ecx, 5
jne     @B

; Loop through array and sum it up
xor     ecx, ecx
xor     eax, eax
@@:
add     eax, [esi + 4 * ecx]
inc     ecx
cmp     ecx, 5
jne     @B
; eax now contains the sum of the array
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }