Access to an array element in assembly language (windows)

I have a problem in assembly language that I got access to an element of an array ... suppose the array contains the days of the week ... like the sun, mon, tues, wed .... I need to access the second index of the array ... How can i do this?

+4
source share
1 answer

Indexing in an assembly is basically the same as C / C ++, with one difference: you must know the size of your data elements.

For example, to iterate over an array of bytes (or characters in a string) in an assembly, you can do the following:

mov eax, 0 mov ecx, 0 loop_start: cmp ecx, ARRAY_LENGTH jge loop_end add eax, BYTE PTR myArray[ecx] add ecx, 1 jmp loop_start loop_end: 

As you can see, the array cycles through one element at a time, increasing ecx (which I use as a counter). Each element is added to eax, which contains the sum at the end of the loop. Notice that I had to add β€œBYTE PTR” when referencing the array to tell the assembler which data type I use.

Now take a look at this code that does the same for DWORD data (4 bytes):

 mov eax, 0 mov ecx, 0 loop_start: cmp ecx, ARRAY_LENGTH jge loop_end add eax, myArray[ecx*4] add ecx, 1 jmp loop_start loop_end: 

Only two things have been changed: I no longer need to use "BYTE PTR" because, unless stated otherwise, the assembler assumes that you are using 32-bit data types on a 32-bit machine; I also needed to change the index of the array to "ecx * 4", because each element in the array has a length of 4 bytes. Most data types used on 32-bit machines are 32 bits in size, so a later example will be more common.

To answer your specific question, here is one way to iterate over an array of strings and display them:

 .data sunday db "Sun",0 monday db "Mon",0 tuesday db "Tues",0 wednesday db "Wed",0 thursday db "Thurs",0 friday db "Fri",0 saturday db "Sat",0 daysOfWeek dd OFFSET sunday, OFFSET monday, OFFSET tuesday OFFSET wednesday dd OFFSET thursday, OFFSET friday, OFFSET saturday .code mov ecx, 0 loop_start: cmp ecx, 7 jge loop_end mov eax, daysOfWeek[ecx*4] ; eax now contains the pointer to the ; next element in the array of days add ecx, 1 jmp loop_start loop_end: 

Since pointers on a 32-bit machine are 32 bits wide, treat them as DWORD, as in the second example.

+11
source

Source: https://habr.com/ru/post/1310212/


All Articles