I have an array where I have to add all two digit numbers, the part with the 2 digit number sorting works , but I can't seem to take the next digit from my array it always takes the first one
.386
.model flat,stdcall
.stack 4096
ExitProcess proto,dwExitCode:dword
.data
skaic DWORD 15,20,12,11,15151515
suma DWORD ?
.code
main proc
mov ecx, 0
l1:
mov ebx,skaic
add ebx,ecx
cmp ebx,15151515
je endl1
add ecx, 4
mov eax,ebx
cmp eax,9
jng l1
add suma, eax
mov eax, 0
mov ebx, 0
jmp l1
endl1:
invoke ExitProcess,0
main endp
end main
CodePudding user response:
Since this is MASM code, the mov ebx, skaic
instruction is retrieving the first element of the array. However seeing the addition with the ECX register and how you raise ECX by 4 throughout the loop, clearly indicates that you expect EBX to contain an address at the same time. It can't be both at once!
The good solution is to maintain a simple pointer that starts by pointing at the first element of the array, and that is incremented by 4 on each iteration of the loop.
mov ebx, OFFSET skaic ; Pointing at the first element
T1:
mov eax, [ebx] ; Retrieving the current element
add ebx, 4 ; Preparing for the next element
cmp eax, 15151515 ; Is it the array terminator
je endT1 ; Yes
cmp eax, 10
jb T1 ; Has fewer than 2 digits, so don't add
add suma, eax
jmp T1
endT1:
Tip1: Don't use label names like l1
. These are hard to read! The mention T1
is already a better choice amongst the non-descriptive label names...
Tip2: It would be a good idea to also insert some array elements that have fewer than 2 digits. If all the array elements have 2 digits, how will you verify that the "number sorting works" ?
From a comment:
... is it possible to somehow , take the last digit of array? because I want to compare the eax to last digit of array and je endloop1
Because the skaic array holds 5 dwords, the last element (we don't talk about 'digit' in this respect), is located at skaic 16
. The offset is 16 because there are 4 elements of each 4 bytes that come before the last element.
In code: cmp eax, [skaic 16]
je endT1
.
Alternatively, because the suma variable follows the skaic array directly in memory, the last element is also found at suma - 4
.
In code: cmp eax, [suma - 4]
je endT1
.