2016-07-09 55 views
0

我想知道这种情况。qsort in C(动态分配)

,当我确定了这句话

struct soccer team[100] ; 

我可以做快速排序;

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

错误。 (快速排序和比较相同)

我想知道如何使用它(快速排序动态分配结构)

请!

例子(当我使用第一种方式)

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 
+0

“的qsort和比较是相同的”是不好的,因为相同的比较函数不应当被用于不同的元素类型。 – MikeCAT

+0

[请参阅此讨论,为什么不在'C'中为'malloc()'和family生成返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

我的迷惘! 原始码:typedef struct soccer SOC; –

回答

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  
+0

是的,我知道了。我想知道当我使用qsort(动态分配)时使用的方式 –

+0

@CherubimAnand不,它是'sizeof * team',检查数据类型。 –

+0

@CherubimAnand正确,但没有任何东西阻止你写'a = malloc(sizeof * a * SIZE));'这可能更好。 –

0

同样的对比功能不能用于不同的元素类型。使用正确的比较函数,像这样的(指向元素,这些元素的指针,将给予,所以取消引用他们获得指针结构):

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

+0

当我插入你的代码时,我的程序还有错误。 –

+0

@박기현请发布一个[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)让我们修复它。 – MikeCAT

0

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

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

team [i] = malloc(sizeof(SOC)); - >是这种类型的错误? –

+0

@박기현你尝试过这个程序吗?这个声明有什么问题? –

+0

错误:无法将类型“void *”的值分配给类型为“SOC *”的实体 –