An array is a data structure typically used to store a series of values. For example, an array may come in handy while storing the salaries of all the employees in a company.
An assembly language directive is required to define the size of each element in the array. In the snippet below, we define an array whose each element is 2 bytes long and assign fib
as its identifier. The DW directive stands for define word:
fib DW 0, 1, 1, 2, 3, 5, 8, 13
Yes, this is the Fibonacci series!
The times
directive can be used to declare an array whose each element is identical. The length of the array must be pre-defined, as seen here:
null TIMES 10 0
The identifier for our array is null
, and its size is 10
. The above code is identical to this one:
null DW 0,0,0,0,0,0,0,0,0,0
To access array elements, we obtain a pointer to the element that we wish to access. The following snippet of code demonstrates how to do this:
mov ecx, [esi];pointer to element at the 0th index stored in the register ecx
mov ecx, [esi+1];pointer to element at the 3rd index stored in the register ecx
mov ecx, [esi+2];pointer to element at the 2nd index stored in the register ecx
The following snippet of code shows how to declare an array of arbitrary size. The identifier for it is arr
, and its size is 3
. Subsequently, it accesses each element of the array and prints it onto the console using the write
system call. We can expect the program to display 123
on the console upon successful execution:
The same program can be rewritten more efficiently using a loop.
section .textglobal _start_start:mov edi, arr ;fetches pointer to arraymov ecx, [edi] ;gets first element in arrayadd ecx, 48 ;converts number in array to charpush ecx ;pushes to stack as we require an addressmov ecx, esp ;obtains the address of the number converted to char in ecxmov edx, 1 ;message length, 1 bytemov ebx, 1 ;file descriptor for stdout streammov eax, 4 ;system call number for the write system callint 0x80 ;call kernelmov edi, arr ;fetches pointer to arraymov ecx, [edi+1] ;gets second element in arrayadd ecx, 48 ;converts number in array to charpush ecx ;pushes to stack as we require an addressmov ecx, esp ;obtains the address of the number converted to char in>mov edx, 1 ;message length, 1 bytemov ebx, 1 ;file descriptor for stdout streammov eax, 4 ;system call number for the write system callint 0x80 ;call kernelmov edi, arr ;fetches pointer to arraymov ecx, [edi+2] ;gets third element in arrayadd ecx, 48 ;converts number in array to charpush ecx ;pushes to stack as we require an addressmov ecx, esp ;obtains the address of the number converted to char in>mov edx, 1 ;message length, 1 bytemov ebx, 1 ;file descriptor for stdout streammov eax, 4 ;system call number for the write system callint 0x80 ;call kernelmov eax, 1 ;system call number of the exit system callint 0x80 ;calls kernelsection .dataarr db 1,2,3section .bss