使用qsort进行C数组排序?

时间:2011-11-15 08:32:57

标签: c arrays sorting data-structures

main.c

#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "head.h"
int comp(const DATA * a, const DATA * b)
{
    return a->size - b->size;
}

int main (int argc, const char * argv[])
{

    // insert code here...
    printf("Hello, World!\n");
    lst = (DATA *) calloc(10,sizeof(DATA));
    lst[0].size = 5;
    lst[1].size = 9;
    lst[2].size = 2;

    qsort(lst,10,sizeof(int),comp);
    printf("this : %i\n ", lst[0]);
    printf("this : %i\n ", lst[9]);

    return 0;
}

head.h

#ifndef main_h
#define main_h
#define DATA struct data

DATA
{
    int size;
    char data;
};

DATA *lst;
int comp(const DATA * a, const DATA * b);
#endif

失败:/

1 个答案:

答案 0 :(得分:6)

  

所以我的起始数组应该看起来像5,9,1,3,0,0,0,0,0,0。

不,不,一千次,不: - )

如果你想在那里使用零,请使用calloc将所有内容归零,或者将它们放入自己。 malloc将为您提供的内容(如原始代码中所示)是具有不确定内容所需大小的块。换句话说,事先记忆中可能有垃圾。

最重要的是,abcomp函数中的指针,您应该使用->而不是. malloc并且使用正确的原型进行铸造是一种很好的形式。

最后一点:请不要从malloc转换回来 - 如果你不小心忘记包含相关的头文件并且你的整数与你的指针不兼容,你可能会遇到问题。

void *函数返回一个#include <stdio.h> #include <stdlib.h> typedef struct {int size; int id;} DATA; int comp (const void *a, const void *b) { return ((DATA *)a)->size - ((DATA *)b)->size; } int main (void) { int i; DATA *myArray = malloc(10 * sizeof(DATA)); myArray[0].size = 5; myArray[1].size = 9; myArray[2].size = 1; myArray[3].size = 3; for (i = 4; i < 10; i++) myArray[i].size = 0; qsort (myArray, 10, sizeof(DATA), comp); for (i = 0; i < 10; i++) printf ("%d ", myArray[i].size); putchar ('\n'); return 0; } ,非常乐意将其隐式转换为任何其他指针。


这是一个包含这些修复程序的完整程序:

0 0 0 0 0 0 1 3 5 9

输出:

{{1}}