About my code searching a element using function pointer

Viewed 33

I was doing a question about finding an element in an array using function pointer concept. But I am facing some issues regarding this. Here is my code.

#include <stdio.h>
#include <stdbool.h>

bool compare( const void* a, const void* b)
{
    return (*(int*)a == *(int*)b);                    
}

int search(const void * arr, int arr_size, int ele_size, void* x, bool compare(const void*, const void*))
{
    char* ptr = *(char**)arr; 
    int i;

    for (i = 0; i < arr_size; i++)
    {
        if (compare(ptr + i * ele_size, x))
        {
            return i;
        }
    }
    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;
}

The code is compile fine but not giving any output? What is wrong with this code?

1 Answers

No need to de-reference arr, just alter its type to do the pointer math.

// char *ptr = *(char**) arr;
const char *ptr = arr;

Minor: Best practice to use const here.

Related