我想知道这种情况。
当我定义这句话的时候
struct soccer team[100] ; 我可以做qsort;
qsort(team, MAX , sizeof(team[0]) , compare) ;
int compare(const void *a, const void *b )
{
SOC *A1 = (SOC*)a ;
SOC *B1 = (SOC*)b ;
if( A1->score > B1->score )
return -1 ;
else if ( A1->score == B1->score )
return 0 ;
else
return 1 ;
}当我做动态分配时
struct soccer*team[MAX] ;
team[Index] = (SOC*)malloc(sizeof(SOC)) ;存在错误。(qsort和比较是相同的)
我想知道如何使用它(动态分配结构的qsort)
请!
示例(当我使用第一种方法时)
Man 3 1 1 16
Che 2 2 2 8
Asn 0 6 0 6
hot 6 0 0 18
City 0 0 6 0
Bar 1 5 0 8已转换为
hot 6 0 0 18
Man 3 1 1 16
Che 2 2 2 8
Bar 1 5 0 8
Asn 0 6 0 6
City 0 0 6 0 发布于 2016-07-09 22:38:43
第一个版本
struct soccer team[100] ;第二个是
struct soccer*team[MAX] ;
team[Index] = (SOC*)malloc(sizeof(SOC)) ;是不一样的。第一个是struct soccer数组,第二个是struct soccer *数组。它们并不是完全一样的。
如果您想使用更高版本(包括指针)并获得与上面相同的行为,您可以这样做
struct soccer * team;
team = malloc(sizeof *team * SIZE) ; // SIZE is the number of elements 发布于 2016-07-09 22:40:14
相同的比较函数不能用于不同的元素类型。使用正确的比较函数,如下所示(将给出指向元素的指针,也就是指针,因此取消对它们的引用以获得指向结构的指针):
int compare2(const void *a, const void *b )
{
SOC *A1 = *(SOC**)a ;
SOC *B1 = *(SOC**)b ;
if( A1->score > B1->score )
return -1 ;
else if ( A1->score == B1->score )
return 0 ;
else
return 1 ;
}发布于 2016-07-09 23:04:45
下面是一个演示程序,它展示了如何对类似的数组进行排序。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
typedef struct soccer
{
unsigned int score;
} SOC;
int cmp( const void *a, const void *b )
{
const SOC *lhs = *( const SOC ** )a;
const SOC *rhs = *( const SOC ** )b;
return ( lhs->score > rhs->score ) - ( rhs->score > lhs->score );
}
int main( void )
{
SOC * team[MAX];
srand( ( unsigned int )time( NULL ) );
for ( int i = 0; i < MAX; i++ )
{
team[i] = malloc( sizeof( SOC ) );
team[i]->score = rand() % MAX;
}
for ( int i = 0; i < MAX; i++ )
{
printf( "%u ", team[i]->score );
}
printf( "\n" );
qsort( team, MAX, sizeof( SOC * ), cmp );
for ( int i = 0; i < MAX; i++ )
{
printf( "%u ", team[i]->score );
}
printf( "\n" );
for ( int i = 0; i < MAX; i++ ) free( team[i] );
return 0;
}程序输出为
2 7 2 5 1 6 1 5 0 4
0 1 1 2 2 4 5 5 6 7https://stackoverflow.com/questions/38282901
复制相似问题