Arrays are fundamental data structures in programming, and assembly language is no exception. In assembly, arrays provide a way to store and access multiple elements of the same data type in contiguous memory locations.
In assembly, arrays are typically declared by reserving a block of memory. The size of this block depends on the number of elements and their data type. Here's a simple example:
section .data
numbers db 1, 2, 3, 4, 5 ; Array of 5 bytes
array_size equ $ - numbers ; Calculate array size
This declares an array named 'numbers' with five byte-sized elements. The array_size
label calculates the total size of the array.
To access array elements, you need to use Memory Addressing Modes. The most common method is base-plus-index addressing:
mov al, [numbers + ecx] ; Load element at index ECX into AL
This instruction loads the element at index ECX into the AL register. Remember, assembly doesn't perform bounds checking, so be cautious to avoid accessing out-of-bounds memory.
Iterating through arrays often involves using Assembly Loops. Here's an example that sums all elements in an array:
section .data
numbers db 1, 2, 3, 4, 5
array_size equ $ - numbers
section .text
global _start
_start:
xor eax, eax ; Clear EAX (our sum)
xor ecx, ecx ; Clear ECX (our counter)
sum_loop:
add al, [numbers + ecx] ; Add current element to sum
inc ecx ; Increment counter
cmp ecx, array_size ; Compare counter with array size
jl sum_loop ; If counter < array_size, continue loop
; EAX now contains the sum of all elements
Assembly doesn't have built-in support for multi-dimensional arrays, but you can simulate them using linear memory and index calculations. For a 2D array, you might use:
mov eax, row_size
mul ebx ; EBX contains the row index
add eax, ecx ; ECX contains the column index
mov al, [array + eax] ; Load element at [row][column]
Arrays in assembly language provide a powerful tool for managing collections of data. While they require more manual management compared to high-level languages, they offer fine-grained control over memory layout and access patterns. By mastering array operations in assembly, you'll gain a deeper understanding of memory management and low-level data structures.
For more advanced topics related to assembly programming, consider exploring Assembly Pointers and Assembly Dynamic Memory Allocation.