I am trying to understand the ff searching algorithm, (that tries to find the index of the element being searched). However, I don't know how it can work with any type of data type. So, the ff questions still remain
- inside the code, it says we can use char pointer since char is only one byte. However, once we made it a char pointer, doesn't it become 8 bytes instead of one byte? also even if it becomes, one byte, how does it help us deal with any type of data(as it claims to do so inside the code)?
- since the whole thing claims, it can work for any type of data, does this work for user-defined data(like structs)? if so, I would appreciate an explanation on how to do so.(i.e. how can we make this work for both int a[] ={7,3,5,7,8,90} and struct student {char name, int score, int id} struct student stude_array [] ={{"Rebeka",92,10},{"Alext",97,11},{"james",90,12}}* data types and search for specific element in each arrays? thank you for your help in advance.
#include <stdio.h>
#include <stdbool.h>
// A compare function that is used for searching an integer
// array
bool compare (const void * a, const void * b)
{
return ( *(int*)a == *(int*)b );
}
// General purpose search() function that can be used
// for searching an element *x in an array arr[] of
// arr_size. Note that void pointers are used so that
// the function can be called by passing a pointer of
// any type. ele_size is size of an array element
int search(void *arr, int arr_size, int ele_size, void *x,
bool compare (const void * , const void *))
{
// Since char takes one byte, we can use char pointer
// for any type/ To get pointer arithmetic correct,
// we need to multiply index with size of an array
// element ele_size
char *ptr = (char *)arr;
int i;
for (i=0; i<arr_size; i++)
if (compare(ptr + i*ele_size, x))
return i;
// If element not found
return -1;
}
int main()
{
int arr[] = {2, 5, 7, 90, 70};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 7;
printf ("Returned index is %d ", search(arr, n,
sizeof(int), &x, compare));
return 0;
}