I am trying to write a generic C function, that returns minimum of an array using function pointers.
The code is :
#include <stdio.h>
int min_index(void *arr, int size, int (*compare)(void *, void *))
{
    int i;
    int min = 0;
    for (i = 1; i < size; i++)
    {
        if (((*compare)(&arr[i], &arr[min])) < 0)
            min = i;
    }
    return min;
}
int comp_int(int *arr1, int *arr2)
{
    if (*arr1 < *arr2)
        return -1;
    else
        return 1;
}
int comp_char(char *arr1, char *arr2)
{
    if (*arr1 < *arr2)
        return -1;
    else
        return 1;
}
int main()
{
    int arr1[5] = {45, 56, 34, 23, 19};
    int index = min_index(arr1, 5, comp_int);  // calling min_index with integer array
    printf("Minimum value in the array is %d\n", arr1[index]);
    char arr2[5] = {'a', 'b', 'c', 'd', 'e'};
    int index2 = min_index(arr2, 5, comp_char); // calling min_index with char array
    printf("Minimum value in the array is %c\n", arr2[index2]);
    return 0;
}
- This code worked for only - chararrays. It did not work for- intarrays.
- I debugged the code. I found that, when I call - min_indexfunction with the integer array, only first value of- arris correct number, but remaining are some garbage values.
- But, when I call - min_indexfunction with character array, all the values are correct. There are no garbage values in this case. I got correct output.
Question : Why does the code work for char arrays not for int arrays ?
 
    