previous | start | next

Assembler Code for 2-Dimensional Array Access

 int a[4][5];      
   

Assume that the array address (i.e., address of a[0][0]) is

 -72(%ebp)
   

and the variables i and j are stored in memory at:

i:  -8(%ebp)
j:  -4(%ebp)
   

What assembler code would do this:

 a[i][j] = 100;
   

Answer: First the address of a[i][j] would be

  -72(%ebp) + 20 * i + 4 * j

or

  -72(%ebp) + 4 * (5 * i + j)
   

The second form is more convenient for using scaled index mode operands

 leal   -72(%ebp), %ecx          ; %ecx: address of a[0][0]
 movl   -8(%ebp), %eax           ; %eax: i
 imull  $5, %eax                 ; %eax: 5 * i
 addl   -4(%ebp), %eax           ; %eax: 5 * i + j
 movl   $100, (%ecx, %eax, 4)    ; a[i][j] = 100
   

where the scaled index address is

 (%ecx, %eax, 4): address(a[0][0]) + 4 * (5 * i + j)
   


previous | start | next