我有一个二进制搜索函数,我正在传递一个指针字符数组、该数组的长度、一个搜索指针字符数组和另一个用于其他内容的计数器。
int binarySearch(char* charArray, int len, char* searchItem, int counter)
{
int position;
int begin = 0;
int end = len-1;
int cond =0;
while(begin <= end)
{
position = (begin + end)/2;
// searchItem is a pointer array and the value I want to compare to is
// at the index of counter (determined outside of this function)
if((cond = strcmp(&charArray[position], &searchItem[counter])) == 0)
{
return position;
}
else if(cond < 0){
begin = position + 1;
}
else
end = position - 1;
}
return -1;
}
从这里开始,手动检查代码似乎让我想认为它应该可以正常工作,但事实并非如此。我想我在我的指针和我如何引用它们的地方被抛弃了,所以正在比较错误的数据。
我已经看了太久了...这里真的需要一些帮助。
最佳答案
不是很清楚在what中搜索什么。但我猜你是在一个排序的字符数组中搜索一个字符。如果是这种情况,则不能使用 strcmp
。相反,您可以这样做:
if(cond = (charArray[position] - *searchItem) == 0)
关于c - 在 c 中的字符数组的特定成员上使用 "strcmp",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9259073/