【问题标题】:qsort in C (dynamic allocation)C中的qsort(动态分配)
【发布时间】:2016-07-09 14:36:37
【问题描述】:

我想知道这种情况。

当我定义这句话时

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 和 compare 是一样的)

我想知道如何使用它(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 

【问题讨论】:

标签: c arrays pointers qsort


【解决方案1】:

第一个版本

 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    

【讨论】:

  • 是的,我知道。我想知道我使用qsort(动态分配)时的使用方式
  • @CherubimAnand不,是sizeof *team,检查数据类型。
  • @CherubimAnand 对,但没有什么能阻止你写a = malloc(sizeof *a * SIZE));,这可能更好。
【解决方案2】:

相同的比较函数不能用于不同的元素类型。像这样使用正确的比较函数(将给出指向元素的指针,即指针,因此取消引用它们以获得指向结构的指针):

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 ;
}

注意:他们说you shouldn't cast the result of malloc() in C

【讨论】:

【解决方案3】:

这是一个演示程序,展示了如何对类似数组进行排序。

#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 7

【讨论】:

  • team[i] = malloc( sizeof( SOC ) ); -> 这种类型的错误吗?
  • @박기현 你试过这个程序吗?这句话有什么问题?
  • 错误:“void *”类型的值不能分配给“SOC *”类型的实体
  • @박기현 在将程序编译为 C++ 程序时,您必须将程序编译为 C 程序。否则你必须写 team[I] = ( SOC * )malloc( sizeof( SOC ) );
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 2011-07-12
相关资源
最近更新 更多