我不知道如何打印数组,反过来,我也无法弄清楚如何交换数组中的元素
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]
一样。将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。
相关文章:
- 通过交换元素使数组相同
- 如何在数组中交换最小和最大的位置?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 如何交换数组中的元素?
- C++:交换矩阵的行:使用单维数组
- 使用指针 c++ 交换结构数组中的元素
- 使用指针交换数组的内容
- C++数组交换并查找最小元素
- 使用指针交换而不引用数组C++
- 指针数组交换无需直接访问数组
- 交换数组
- 如何在C++中交换对象数组的 2 个不同对象
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 在C++中使用 2D 数组进行交换
- 在2D数组中交换行的最佳方法
- 优化C++中的字符数组成员交换
- 具有记录数组的C++交换函数
- C++:反转数组中的字符串.在两个不同的数组之间交换字符串
- 如何找到在两个不同数组中交换的值
- uniqueptr-在多维c++数组中交换unique_ptr