In my lSearch function (linear search), I am trying to pass by reference a variable named *numComparisons.
Everytime a comparison is made it should increment but for some reason it is not doing this. Why not? When it goes to the end of main.. the function does work (as in it’ll find a comparison or it will return -1 if no comparison is found) but the numComparisons value outputs to 0 everytime.
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;
Change
to
Postfix increment has higher precedence than the dereference operator, so your code increments the pointer instead of incrementing the pointed-to value.