I performed an "experiment" to test my understanding of pointers in C. I decided to write a linear search function that can work on any array provided there is an existing function to compare the elements of the array. Here are the files:
linear_search.h
#ifndef _LINEAR_SEARCH_H
#define _LINEAR_SEARCH_H
/*
* Summary:
* Performs linear search on the given array using the given
* comparator function. Returns the index of the matching array
* element (< len), and -1 if the element is not found.
*
* Parameters are independent of type and hence this function
* can be used for arrays of all data-types, provided that the width
* (i.e. size of the datatype in terms of bytes) is properly specified.
*
* Parameters:
* 1. *base - the address of the array from whence we start searching.
* 2. *x - the address of the element to find in the array
* 3. len - the maximum number of elements we are willing to search against.
* 4. width - the width of each element of the array (in bytes)
* 5. compare(void*, void*)
* - the function which is used for comparison. Zero is taken to be equality.
*/
long long linear_search
(
const void *base, const void *x, const long long len, const int width,
const int (*compare)(const void *, const void *)
);
#endif
linear_search.c
long long linear_search
(
const void *base, const void *x, const long long len, const int width,
const int (*compare)(const void *, const void *)
)
{
long long index = 0;
// convert to a char * pointer in order to make the pointer arithmetic in terms of 1 byte
char *base_ptr = (char *) base;
for (; index < len; index++) {
if ((*compare)((base_ptr + index * width), x) == 0)
return index;
}
return -1;
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "linear_search.h"
const int compare(const void *a, const void *b)
{
double *p = (double *) a;
double *q = (double *) b;
return *p - *q;
}
int main(int argc, char const *argv[])
{
double *a;
double x;
int width;
long long int index, len, i;
width = sizeof(double);
printf("Enter how many elements : ");
scanf("%lld", &len);
a = malloc(len * width);
if (a == NULL) {
printf("Error while trying to allocate memory.\n");
return EXIT_FAILURE;
}
printf("Enter elements one-by-one:\n");
for (i = 0; i < len; i++) {
printf("%d : ", (i + 1));
scanf("%lf", (a + i));
}
printf("Enter the element to look for : ");
scanf("%lf", &x);
index = linear_search(a, &x, len, width, compare);
printf("Index is %lld\n", index);
return EXIT_SUCCESS;
}
I would like to know if there's a better way to accomplish this task, or if I'm making any gross errors. While it's true that my program compiled without any errors or warnings, I am never sure when it comes to C. Suggestions (however small) and critique is welcome.