1.20. ARRAYS
ret 0
get_by_coordinates2 ENDP
array$ = 8
a$ = 16
b$ = 24
get_by_coordinates1 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
ret 0
get_by_coordinates1 ENDP
GCC also generates equivalent routines, but slightly different:
Listing 1.247: Optimizing GCC 4.9 x64
; RDI=address of array
; RSI=a
; RDX=b
get_by_coordinates1:
; sign-extend input 32-bit int values "a" and "b" to 64-bit ones
movsx rsi, esi
movsx rdx, edx
lea rax, [rdi+rsi4]
; RAX=RDI+RSI4=address of array+a4
movzx eax, BYTE PTR [rax+rdx]
; AL=load byte at address RAX+RDX=address of array+a4+b
ret
get_by_coordinates2:
lea eax, [rdx+rsi4]
; RAX=RDX+RSI4=b+a4
cdqe
movzx eax, BYTE PTR [rdi+rax]
; AL=load byte at address RDI+RAX=address of array+b+a4
ret
get_by_coordinates3:
sal esi, 2
; ESI=a<<2=a4
; sign-extend input 32-bit int values "a4" and "b" to 64-bit ones
movsx rdx, edx
movsx rsi, esi
add rdi, rsi
; RDI=RDI+RSI=address of array+a4
movzx eax, BYTE PTR [rdi+rdx]
; AL=load byte at address RDI+RDX=address of array+a4+b
ret
Three-dimensional array example
It’s the same for multidimensional arrays.
Now we are going to work with an array of typeint: each element requires 4 bytes in memory.
Let’s see:
Listing 1.248: simple example
#include <stdio.h>
int a[10][20][30];
void insert(int x, int y, int z, int value)
{
a[x][y][z]=value;
};