J Mei J Mei - 1 month ago 7x
C Question

How can I search through an array that returns both the position of the value and the number of comparisons?

I have a function that searches an array for a given value and returns its position if found. However, I also want it to update the number of comparisons it took to search through the entire array. But it is not working and crashes once it exits the function and calls for the parameter.

int linSearch(int arr[], int size, int target, int* numComparisons) {
int i;
int count = 0;

for (i = 0; i < size; i++) {
if (arr[i] == target) {
numComparisons = count;
return i;
return -999;

I am calling the function with this

linSearch(userArray, userEntries, valSearch, *numLinSearch)

and the variable numLinSearch is this

int *numLinSearch = 0;

When i try to print out something like printf("%d", numLinSearch); the program crashes. How do I fix this?

md5 md5
numComparisons = count;

You are changing the value of the pointer, not value of the pointed object. It should be rather:

*numComparisons = count;

numComparisons has to contain the address of a variable so that the function can process its data. Therefore you should call linSearch like this:

int numComparisons = 0; /* for example */
linSearch(userArray, userEntries, valSearch, &numLinSearch)

rather than:

int *numComparisons = 0; /* numComparisons is a null pointer */