[英]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,6
以add 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.