【发布时间】:2015-05-13 08:45:51
【问题描述】:
我正在尝试使用汇编创建冒泡排序。我已经使用几乎相同的代码成功地完成了这项工作,只是现在我传入了一个LOCAL 数组,而不是.data 部分中定义的数组。一切都在运行,但似乎没有切换。
这里是代码
start
call main
exit
main PROC
LOCAL numArray[5]:DWORD ; Create a local array for the numbers
mov [numArray + 0], 5
mov [numArray + 4], 4
mov [numArray + 8], 3
mov [numArray + 12], 2
mov [numArray + 16], 1
push numArray
call BubbleSort
ret
main ENDP
array EQU [ebp + 8]
FLAG EQU DWORD PTR [ebp - 4]
BubbleSort PROC
enter 4, 0 ; Enter with one int local memory (for flag)
outer_bubble_loop:
mov ecx, 1 ; Set the count to 1
mov FLAG, 0 ; And clear the flag (Detects if anything changes
inner_bubble_loop: ; Loop through all values
mov ebx, [array + ecx * 4 - 4] ; Move the (n - 1)th index to ebx
cmp ebx, [array + ecx * 4] ; Compare ebx against the (n)th index
jle end_loop ; If the result was less than or equal, skip the swapping part
mov ebx, [array + ecx * 4] ; Move (n) into ebx
mov edx, [array + ecx * 4 - 4] ; Move (n - 1) into edx
mov [array + ecx * 4], edx ; Move (n - 1) into n
mov [array + ecx * 4 - 4], ebx ; Move (n) into (n - 1)
mov FLAG, 1 ; Set the changed flag
end_loop: ; End loop label
inc ecx ; Increase the count
cmp ecx, NDATES ; Check if we've made it to the end yet
jl inner_bubble_loop ; If not, repeat the inner loop
cmp FLAG, 0 ; Check if we changed anything
je loop_end ; If we didn't, go to the end
jmp outer_bubble_loop ; (Else) Jump to the beginning of the loop
loop_end: ; Loop end label
leave
ret
BubbleSort ENDP
奇怪的是,我的输出是:
4
5
5
2
1
如果我使用不同的数据集,它不会进行复制,但仍然没有移动。
我哪里错了?
【问题讨论】:
-
在我的旧版 Masm 中,
LOCAL指令仅在宏中使用,以强制宏为宏中的任何标签生成唯一标识符(因此它们不会在其他用法中重复宏)。 -
@WeatherVane,来自 Assembly Language for x86 Processors,第 6 版,“我们可以猜测 Microsoft 创建了 LOCAL 指令作为 ENTER 指令的高级替代品。LOCAL按名称声明一个或多个局部变量,并为其分配大小属性。(另一方面,ENTER 只为局部变量保留一个未命名的堆栈空间块。)”此外,示例从未表明它只能在宏中使用.实际上,他们甚至从不使用宏来展示它们。
-
如风向标所说的使用
-
@David 确实,我的 Masm 使用
ENTER(和LEAVE)为局部变量设置堆栈框架。 -
@WeatherVane,根据书中的说法,替代方案是只使用
LOCAL。