【发布时间】:2019-08-17 14:03:42
【问题描述】:
我正在编写代码来查找数组中的最后一个 0。
基本上我需要在每个数组的“顶部”移动一个新值,如果它只有零,则将其放在末尾,如果找到其他值,则将其放在最后一个 0(我正在对待我的数组作为堆)。
到目前为止,我的子例程在大多数情况下都可以正常工作,但有时它会重写一个我不想要的值(而不是获取与 0 不同的第一个值,而是获取下一个值)。这是我用来获取数组“顶部”的代码。
TOP:
xor ecx,ecx
xor ebx,ebx
TOP_FOR:
mov bx,word[eax+ecx*2] ;eax has the pointer of the array
cmp ecx,n ;n is the array's length
je END_TOP
inc ecx
cmp bx,0
je TOP_FOR
;here i get the direction of the first value different
END_TOP: ;from 0 but in my code i need the last 0, so
dec ecx ;i decrease ecx (result of this subrutine)
ret
例如,
如果我放置一个 0,2 的数组,我期望 ecx = 0,但使用该输入实际上得到 1。
- 使用数组 1,2 我得到 0(这是我想要的)
- 使用数组 0,0 我得到 1(我想要的,再次)
编辑:尝试在 n-1 上启动循环,它给了我更奇怪的结果。
TOP:
xor ecx,ecx
;xor ebx,ebx
mov ecx,n-1
TOP_FOR:
;mov bx,word[eax+ecx*2]
cmp word[eax+ecx*2],0
je FIN_TOPE
dec ecx
cmp ecx,0
jne TOP_FOR
END_TOP:
ret
【问题讨论】:
-
您更新的代码不会运行
i=0的循环体,因此它从不查看第一个元素。这就是我在回答中使用dec ecx / jge的原因;它仅在 ECX 变为-1后才离开循环。另请注意,dec设置标志,您不需要单独的cmp和 0。