它执行两个块的字典比较。我使用各种类型的块测试我的程序。 字符测试都是货物。第一次测试不好,因为好的答案是 0,但现在是 1。第二次测试正常 (1 == 1) 第三次测试正常 (-1 == -1) 帮助我进行第一次测试。谢谢
这是我的代码:
int compare_ints(const void* v1, const void* v2) {
int *a = (int*)v1;
int *b = (int*)v2;
if (*a == *b) return 0;
else if (*a > *b) return 1;
else return -1;
}
int compare_gen(const void *block1, const void *block2,
size_t elem_size, size_t block1size, size_t block2size,
int (*compare_it)(const void*, const void*)) {
int i = 0;
int result = -2;
if ( elem_size == sizeof(char) )
{
while ( i < block1size && i < block2size)
{
result = (*compare_it)((&((char*)block1)[i]),(&((char*)block2)[i]));
if ( result == 0)
{
i++;
}
else if ( result == -1 || result == 1 )
{
return result;
}
}
if ( result == 0 )
{
if (i == block1size && i == block2size)
{
return result;
}
else if (i != block1size && i == block2size)
{
result = -1;
return result;
}
else
{
result = 1;
return result;
}
}
}
else if (elem_size == sizeof(int))
{
while ( i < block1size && i < block2size)
{
result = (*compare_it)((&((int*)block1)[i]),(&((int*)block2)[i]));
if ( result == 0)
{
i++;
}
else if ( result == -1 || result == 1 )
{
return result;
}
}
if ( result == 0 )
{
if (i == block1size && i == block2size)
{
return result;
}
else if (i != block1size && i == block2size)
{
result = -1;
return result;
}
else
{
result = 1;
return result;
}
}
}
return result;
}
int main()
{
int array1 [10] = {10};
int array2 [10] = {10};
int array3 [10] = {10};
int array4 [9] = {10};
int i;
for (i = 0; i < 10; i++) {
array1[i] = 10;
array2[i] = 10;
array3[i] = 10;
if (i < 9) array4[i] = 10;
}
array3[5] = 9;
// First test
int result = compare_gen(array1, array2, sizeof(int), sizeof(array1), sizeof(array2), (&compare_ints));
printf("1 --> %d\n",result);
// Second test
result = compare_gen(array1, array3, sizeof(int), sizeof(array1), sizeof(array3), (&compare_ints));
printf("2 --> %d\n",result);
// third test
result = compare_gen(array1, array4, sizeof(int), sizeof(array1), sizeof(array4), (&compare_ints));
printf("3 --> %d\n",result);
return 0;
}