我不知道如何打印数组,反过来,我也无法弄清楚如何交换数组中的元素

I can't figure out how to print arrays and in turn, I can't figure out how to swap elements in an array

本文关键字:数组 何交换 弄清楚 交换 元素 反过来 打印 何打印 我不知道      更新时间:2023-10-16

这是c++文件:

#include <iostream>
using namespace std;
//This is the C prototype of the assembly function, it requires extern"C" to
//show the name is going to be decorated as _test and not the C++ way of
//doing things
extern"C"
{
    //char arrayReverse(char*, int);
    int numChars(char *, int);
    char swapChars(char *, int);
}
int main()
{
    const int SIZE = 7;
    char arr[SIZE] = { 'h', 'e', 'l', 'l', 'o', '1', '2' };
    int val1 = numChars(arr, SIZE);
    cout << "The number of elements is: " << val1 << endl;
    char val2 = swapChars(arr, SIZE);
    cout << "Swapped! " << endl;

    return 0;
}

和我的swapChars()文件:

    .686
    .model flat
    .code
    _swapChars PROC ; named _test because C automatically prepends an underscode, it is needed to interoperate
        push ebp
        mov ebp,esp ; stack pointer to ebp
        mov ebx,[ebp+8] ; address of first array element
        mov ecx,[ebp+12] ; number of elements in array
        mov ebp,0
        mov eax,0
        mov edx,ebx     ;move first to edx
        add edx, 7      ;last element in the array
    loopMe:
        cmp ebp, ecx        ;comparing iterator to total elements
        jge nextLoopMe
        mov eax, [ebx]      ;move 1st element into tmp eax
        mov ebx, [edx]      ;move last element into first
        mov edx, eax        ;move tmp into last
        push ebx            ;push first element onto stack
        add ebx, 1          ;first + 1
        sub edx, 1          ;last - 1
        add ebp, 1          ;increment
    jmp loopMe


        nextLoopMe:
            mov ebx,[ebp+8] ;find first element again  USING AS FFRAME POINTER AGAIN
            cmp ebx, ecx    ;comparing first element to number of elements
            je allDone
            pop ebx
            add ebx, 1
        jmp nextLoopMe
    allDone:    
        pop ebp
        ret
    _swapChars ENDP
    END 

这应该取arr[0]中的值,并将其与arr[6]、arr[1]与arr[5]等进行交换,直到整个数组被交换,然后显示它。我不知道我写的代码是否有任何我想做的事情,但我正在寻找一种方法来查看发生了什么。

有没有一种方法可以让asm代码在循环中迭代时将内容打印到控制台?

寄存器([ebx])周围的括号是否表示寄存器的值?

在loopMe:中时,第三行

mov eax, [ebx]

我得到一个异常"assignment4.exe中0x012125FC处引发异常:0xC0000005:读取位置0xCCCCCCCD的访问冲突。"

我处理掉期是否正确?

谢谢你抽出时间。

您确实需要学习使用调试器来逐步完成这项工作。也就是说,我看到了一些问题。

add edx,7

会将edx指向数组的末尾。就像C代码中的arr[7]一样。将edx指向最后一个字符应该是add edx,6

在进程中间更改ebp是很容易出错的,我认为你有一个错误。您更改了它的值,但希望[ebp+8]稍后引用相同的数据。

您也没有正确修改列表。要将字符从一个元素移动到另一个元素,您可以执行以下操作:

mov al, [ebx]     ; copy byte from address ebx to register al
mov [edx], al     ; copy byte in register al into address edx

eax寄存器为32位,一次将复制4个字节,而不是1个。

首先,您的代码是不安全的,因为您忘记在char数组的末尾添加\0。当您使用函数处理您的char或char字符串时,它将引发内存泄漏。大小应为8,数组中的最后一个应为\0。