如何解决x64汇编中的线性搜索未返回正确的索引
我正在尝试在x64程序集中编写一个线性搜索子例程,以返回目标的索引 它需要四个参数。此函数将迭代扫描整个数组,直到找到目标元素或到达数组末尾为止。该函数接受三个参数。第一个参数是一个指向int数组的指针。第二个参数是代表数组大小的整数。第三个参数是一个整数,表示要在数组中找到的目标元素。此函数的返回类型为int,它将是找到目标的数组的索引;如果未找到,则为-1
int linearSearch(int * arr,int size,int target){
int a;
int index = -1;
for(int i = 0; i < size; i++){
if(arr[i] == target){
index = i;
break;
}
}
return index;
}
这是我的代码
global linearSearch
linearSearch:
;the prologue
xor rax,rax ;zero out the return address
xor r10,r10 ;zero out the counter
linearSearchIterative:
;function body
mov rax,-1 ;int index = -1 if not found
cmp r10,rsi ;compare counter i with the size
je done ;done with the program
cmp rdx,[rdi+4*r10] ;compare target with arr[i]
je linearSearchAlter ;jump to the index fixing part if arr[i] == target
inc r10 ;i++
jmp linearSearchIterative ;go back to the start of the loop
linearSearchAlter:
;This part change the return index to where the target is
mov rax,r10 ;index = i
jmp done ;end the loop
done:
ret
但是,子例程仅返回-1,这是不期望的。 我正在使用一个测试cpp文件来测试我的代码,该代码应该能够提供令人满意的预期结果
#include <iostream>
#include <cstring>
using namespace std;
extern "C" int linearSearch(int * arr,int target);
int main(){
int size;
// prompt for array size
cout << "Enter the array size: ";
cin >> size;
int * arr = new int[size];
// read in array values
for(int i = 0; i < size; i++) {
cout << "Enter value " << i << ": ";
cin >> arr[i];
}
int target;
// prompt for target
cout << "Enter target to search for: ";
cin >> target;
int ind = linearSearch(arr,size,target);
cout << ind << endl;
if (ind > -1)
cout << "\nFound " << target << " at index " << ind << endl;
else
cout << "\nDid not find " << target << endl;
return 0;
}
预期结果应该是(我添加了一条打印语句以检查索引值)
Enter the array size: 5
Enter value 0: -7
Enter value 1: 2
Enter value 2: -39
Enter value 3: 12
Enter value 4: 8
Enter target to search for: 2
1
Found 2 at index 1
相反,我的结果是(我添加了一条打印语句以检查索引的值)
Enter the array size: 5
Enter value 0: -7
Enter value 1: 2
Enter value 2: -39
Enter value 3: 12
Enter value 4: 8
Enter target to search for: 2
-1
Did not find 2
因此,子例程似乎总是返回-1而不是目标的索引。问题应该在哪里?谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。