使用qsort进行C数组排序?

ant*_*pug 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

失败:/

pax*_*blo 6

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

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

如果你想在那里使用calloc零,要么将所有内容归零,要么将它们放入自己.什么malloc会给你(如在你的原始代码中)是一个具有不确定内容所需的大小块.换句话说,事先记忆中可能有任何垃圾.

而且,最重要的是,a并且b是你的函数中的指针comp,你应该使用->而不是.并且它是良好的形式来使用正确的原型与铸造.

最后要注意的是:请不要转发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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0 0 0 0 0 0 1 3 5 9
Run Code Online (Sandbox Code Playgroud)