在我的 lSearch 函数(线性搜索)中,我试图通过引用传递一个名为 *numComparisons 的变量。
每次进行比较时,它都应该增加,但由于某种原因它没有这样做。为什么不?当它走到 main.. 的末尾时,该函数确实可以工作(因为它会找到一个比较,或者如果没有找到比较,它将返回 -1)但 numComparisons 值每次都输出为 0。
int lSearch(int arr[], int size, int target, int *numComparisons)
{
int counter;
for(counter = 0; counter < size; counter++)
{
*numComparisons++;
if(arr[counter] == target)
return(*numComparisons);
}
return(-1);
}
int main(int argc, char * argv[])
{
int enterNumbers[1000], copy[1000], counter;
int numComparisons = 0, target = 26;
printf("Enter in numbers and press -999 when you are done: ");
for(counter = 0;; counter++)
{
scanf("%d", &enterNumbers[counter]);
if(enterNumbers[counter] == -999)
break;
}
arrayCopy(enterNumbers, copy, counter);
sort(copy, counter);
if(lSearch(copy, counter, target, &numComparisons) >=0)
{
printf("Target number found in linear search.\n");
printf("Number of comparisons: %d\n", numComparisons);
}
else
{
printf("Target number was not found in the linear search\n");
printf("Number of comparisons: %d\n", numComparisons);
}
return 0;