我正在尝试执行以下操作:
- 为维度为 7 的数组分配内存
- 写出前 4 个位置
- 对这 4 个位置进行排序。
- 写出剩余的 3 个位置
- 对整个数组进行排序。
我有数组(1,6,2,3)
,排序后变成(1,2,3,6)
然后我写下剩余的位置,即(1,2,3,6,1,5,1)
排序后,我应该得到(1,1,1,2,3,5,6)
,但我却得到了
(6,2,3,1,1,5,1)
。
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int comp(const void* a, const void* b);
typedef struct{
int peso;
}aresta_;
int main(int argc, const char * argv[]) {
aresta_* array /*struct array, has field peso of type int*/;
int dim=7;
int dim_aux=4;
int i;
array = (aresta_*) malloc(dim * sizeof(aresta_));
array[0].peso=1;
array[1].peso=6;
array[2].peso=2;
array[3].peso=3;
printf("First sort:\n");
for(i=0; i<dim_aux; i++)
printf("%d ",array[i].peso);
printf("\n");
qsort(array, dim_aux, sizeof(array[0]), comp);
for(i=0; i<dim_aux; i++)
printf("%d ",array[i].peso);
printf("\n\n");
array[4].peso=1;
array[5].peso=5;
array[6].peso=1;
printf("Second sort:\n");
for(i=0; i<dim; i++)
printf("%d ",array[i].peso);
printf("\n");
qsort(array, dim, sizeof(array[0]), comp);
for(i=0; i<dim; i++)
printf("%d ",array[i].peso);
printf("\n");
}
我的补偿功能:
int comp(const void* a, const void* b)
{
aresta_* a1 = (aresta_*)a;
aresta_* b1 = (aresta_*)b;
return a1->peso > b1->peso;
}
输出:
First sort:
1 6 2 3
1 2 3 6
Second sort:
1 2 3 6 1 5 1
6 2 3 1 1 5 1
Program ended with exit code: 0
我哪里出错了?任何帮助将不胜感激。
最佳答案
OP的函数只返回0和1。@Weather Vane
因为这对 OP 的前 4 个值“有效”,所以是“运气”。
比较函数需要返回 3 个结果中的 1 个:负数、0 或正数。
The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
C11dr §7.22.5.2 3
int comp(const void* a, const void* b)
{
const aresta_* a1 = (const aresta_*)a;
const aresta_* b1 = (const aresta_*)b;
// return a1->peso > b1->peso;
return (a1->peso > b1->peso) - (a1->peso < b1->peso);
}
return (a1->peso > b1->peso) - (a1->peso < b1->peso);
比return a1->peso - b1->peso;
有优势。这个答案不会溢出。它对于所有 int
对都是有效且功能正确的。 。各种编译器都能识别这种习惯用法并生成紧凑的代码。 int - int
可能会溢出,这是未定义的行为,UB。
关于C qsort 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723947/