Search code examples
arraysloopsassemblyx86masm

How to access two dimmensional arrays in MASM


Can you show me how I can access two dimmensional arrays in MASM?

C++ code:

int k = 0
    for (i = 0; i<5; ++i)
    {
        if (k == text.length())break;
        for (j = 0; j<2; ++j)
        {
            for (t = 0; t<26; ++t)
            {
                if (text[k] == letters[t]){ tab[i][j] = t; k++; break; }
            }
        }
    }

MASM

mov al, [ebx]       ;ebx - begin of text array          
xor esi, esi        
for1:
cmp al, 00                  
je break_for1                   
mov j, 0        
for2:
mov t, 0                    
mov ecx, adrAlphabet        ;ecx - begin of letters array           
for3:               
;if (text[k] == letters[t]){ tab[i][j] = t; k++; break; }
mov ah, [ecx]               
cmp ah, 00                      
je end_of_alphabet              
cmp al, 00                      
je end_of_text                  
cmp al, ah                          
jne not_equal
;here comes the problem
        mov edx, t                      
        mov [letters + (esi*4 + j)*4], edx
;   
inc k                           
inc ebx                         
jmp break_t                 
; end if
not_equal:
inc ecx                         
inc t                       
cmp t, 26                       
jne for3

break_t:
inc j                           
cmp j, 2                    
jne for2

inc esi                             
cmp esi, 5                      
jne for1

break_for1:
end

That's only part of my code, but I just want understand arrays. Can you give some example how I can use tab[i][j] in MASM? Another question is, how I can modify the length of tab array? In short: at start of program the tab size will be calculated, then I want to set array size.

Thanks


Solution

  • A two dimensional array of size [a][b] is guaranteed by the C++ standard to be equivalent to a single one dimensional array of size [a*b]. You can stop thinking of it as a two dimensional array and just think of it as a normal array, just a contiguous chunk of data.

    That is, if you want to access tab[i][j] it's exactly the same as accessing tab+a*i+j

    If you know that a (the number of rows in our array) is always 2, 4, or 8 you can directly use an expression of the form

    mov byte ptr [eax*8+ecx], someValue

    Where i is eax and j is ecx.

    Otherwise you will have to compute i*a+j manually, using shifts or imul and use that as an index into your array.

    For exemple:

    ; Write 0 at tab[i][j]
    ; We use EDX because of how IMUL works
    mov edx, i ; EDX = i
    imul a ; EDX = i*a
    add edx, j ; EDX = i*a+j
    add edx, offset tab ; EDX = tab[i*a+j] = tab+i*a+j
    mov byte ptr [edx], 0