繁体   English   中英

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

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

这是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]一样。 应该add edx,6add edx,6指向最后一个字符。

在proc的中间更改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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM