我尝试了一个在 c 中使用通用比较函数的简单示例,但是在初始化它时,我收到警告消息,指出初始化它们时类型不兼容。感觉我在这里缺少一些基本的东西......
#include <stdio.h>
#include <string.h>
int
compare(int (*comp)(void *first, void *second), void *arr, int size)
{
int i, j, dups=0, arrsize=sizeof(arr)/size;
for(i=0; i<arrsize; i++)
{
for(j=0; j<arrsize; j++)
{
if(j!=i)
dups+=(*comp)(&arr[i], &arr[j]);
}
}
return dups;
}
int
compareints(int *first, int *second)
{
if(*first==*second)
return 1;
return 0;
}
int main(int argc, const char * argv[])
{
int (*comp)(void *, void *)=&compareints; //Here is where I get the warning...
int arr[10]={22, 39, 78, 22, 99, 12, 82, 10, 11, 28};
printf("The arr has dups: %d\n", compare(comp, arr, sizeof(int)));
return 0;
}
编辑:程序运行不正常,它与数组的处理有关。功能编的修改如下:
int
compare(int (*comp)(void *first, void *second), void **arr, int size)
....
....
....
dups+=(*comp)(arr[i], arr[j]);
int
compareints(....)
if((*((int *)first))==(*((int *)second)))
return 1;
int
main(int argc, const char * argv[])
{
int (*comp)(void *, void *)=&compareints;
int arr[10]={22, 39, 78, 22, 99, 12, 82, 10, 11, 28};
void **arr2=malloc(sizeof(int *)*10);
for(int i=0; i<10; i++)
{
arr2[i]=&arr[i];
}
printf("The arr has dups: %d\n", compare(comp, arr2, 10));
return 0;
}