0

i'm trying to write a code that print all array elements and print the sum of it, also it copy the a1 elements's and paste in a2 note the type of arrays should be byte it works but it is print the sum is 9 rather than 45 i didn't know what is the error!

.data
a1 byte 0,1,2,3,4,5,6,7,8,9
a2 byte 10 dup(?)
space byte "  ",0
var1 byte "the sum is: ",0dh,0ah
total word 0

.code
main PROC
mov ecx,10
mov edi, 0
mov eax,0

xx:
movzx eax,byte ptr a1[edi]
call writedec
mov edx,offset space
call writestring
add edx, eax
mov bl,a1[edi]
mov a2[edi],bl
inc edi
loop xx

mov edx, offset space
call writestring
mov edx,offset var1
call writestring
mov bx, total
call Writedec

   

exit
  • Might be that `ax` is destroyed by calls to `writedec` and/or `writestring`? If it's not preserved by those procs your code is wrong and the `total` calculation needs to be changed. – Paweł Łukasik Sep 26 '22 at 22:06
  • Moving up the `add total, ax` to just after the `movzx` is good practice anyway. Also, you forgot to show the code that actually prints the total. – Jester Sep 26 '22 at 23:30
  • 1
    @PawełŁukasik: The irvine32 functions have a custom calling convention that preserves all registers (unless there's a return value, which output functions like [writedec](https://csc.csudh.edu/mmccullough/asm/help/source/irvinelib/writedec.htm) / writestring don't have). It's a good habit to learn because the real world isn't like that, but that isn't the problem here. Presumably they just print `EAX` after this, which holds the last `a1` element, not `total`. – Peter Cordes Sep 27 '22 at 03:55
  • And it's weird that this code loads into 16-bit AX instead of just zero-extending to 32-bit EAX; you can still `add total,ax` to use the low half of that, or keep the total in a register and store it once after the loop. And no need to load `a1[edi]` twice, just `movzx eax, byte ptr a1[edi]` / `add edx, eax` / `mov a2[edi], al` / `call writedec`. (`writedec` preserves ECX as well as EAX and EDX, that's why the loop works at all.) – Peter Cordes Sep 27 '22 at 04:01
  • It still print 9 instead of 45 – user20083757 Sep 27 '22 at 04:58
  • 1
    `mov bx, total` - There's your problem. Like I guessed, you're not loading `total` into EAX (the arg for `WriteDec`), just leaving the last array element there. – Peter Cordes Sep 27 '22 at 05:56
  • Basically a duplicate of [cant understand why certain variable is being altered](https://stackoverflow.com/q/54737788) - WriteDec takes its arg in EAX. – Peter Cordes Sep 28 '22 at 03:17

0 Answers0