Reputation: 4185
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;
Upvotes: 1
Views: 1353
Reputation: 639
*numComparisons++
means first the pointer is incremented by 4(helpful while using arrays)
Use (*numcomparisons)++
to increment the int
pointed by numcomparisons
Upvotes: 0
Reputation: 16582
*numComparisons++;
Doesn't increment the int
at that pointer, it increments the pointer itself.
You need to add appropriate parentheses:
(*numComparisons)++
Upvotes: 1
Reputation: 500367
Change
*numComparisons++;
to
(*numComparisons)++;
Postfix increment has higher precedence than the dereference operator, so your code increments the pointer instead of incrementing the pointed-to value.
Upvotes: 6