nasm将两个数组一个接一个地添加到第三个数组中

时间:2011-04-08 18:53:39

标签: assembly nasm

在32位架构上工作,我将两个数组一个接一个地插入到第三个数组中,所以如果我在数组中有3,4,4和4,4,4,那么第三个数组应该包含7个,功能结束时的8,8

我能够正确地传入数组并将项目数量传入函数arleady,我知道这是因为我运行了测试代码

现在我正在研究它的附加部分,这就是我所拥有的,逻辑对我来说是有意义的,但它仍然是错误的......想法?

;*************************************ADD ARRAY**********************************************
segment .bss
;
segment .data
summessage  db  "The Sum is: ", 0
segment .text
extern readdouble,print_string, read_int, writedouble, print_nl, print_int
    global addarray
addarray:
    pusha
    mov edi, 0      ;initialize counter to 0
    mov ecx, 0      ;zero out ecx and edx
    mov edx, 0

    mov ebx, [esp+48]   ;moves starting location of array1 into ebx
    mov edi, [ebp+40]   ;move quantity into edi 
    mov ebp, [esp+60]   ;move the starting location of array2 into ebp

    mov esi, [esi]  ;move starting locatino of array3 into esi

    ;mov    ecx, [ebp]
    ;mov    edx, [ebp+4]
    ;call   writedouble
    ;call   print_nl

add_loop:

    fld     qword [ebx]      ;The second input is now in a floating point register, specifically st0.
    fld qword [ebp]

    fadd                 ;The first input is added to the second input and the sum
                         ;replaces the second input in st0

    fstp    qword [ecx] ;copy top of stack onto ecx
    mov ecx,[ecx]
    mov edx,[edx+4] 

    mov [esi], ecx
    mov [esi+4], ecx
    add esi, 8      ;increment to the next loaction of esi

    add ebx,8       ;increment location of ebx to the next floating point value of array1
    ;add    ebp,8       ;increment location of ebp to the next floating point value of array2

    dec edi     ;increment counter

    cmp edi, 0      ;compare to see if all values have been added
    jz  add_done
    jmp add_loop
add_done:
    popa
    ret

1 个答案:

答案 0 :(得分:1)

段错误可能来自fstp qword [ecx]。在addarray的开头,将ecx设置为0,然后尝试在该地址存储一个值,系统不允许该值。正如Brendan所提到的,您可以直接将值存储到输出数组中:

; This replaces five lines starting with your current fstp instruction
fstp qword [esi]

接下来,你为什么评论ebp的增量?有了这个注释,您将始终将第二个数组的第一项添加到第一个数组的当前元素。

最后,您可以通过两条指令缩短确定是否需要另一个循环的代码。 dec如果结果为0则自动设置零标志,因此您不需要cmp指令,如果它不为零,您可以告诉它转到另一个循环,但只是让它继续如果是:

dec edi ; decrement number of remaining elements
jnz add_loop
; If edi is zero, this will just continue into add_done

编辑为Brendan建议直接存储到输出数组