简体   繁体   English

在 C 中使用 typedef 结构进行 qsort

[英]qsort with typedef structs in C

After searching in lots of posts, I cannot solve my problem.在搜索了很多帖子后,我无法解决我的问题。 I want to order an array of structs depending on one field (deadline):我想根据一个字段(截止日期)订购一组结构:

typedef struct{
    int ident;
    int computation;
    int period;
    int deadline;
}task_t;
task_t *tasks;

int compare(const void *a, const void *b) {

        task_t *ia = *(task_t**)a;
        task_t *ib = *(task_t**)b;
        //task_t *ia = (task_t *)a;
        //task_t *ib = (task_t *)b;

        return (ia->deadline - ib->deadline);
}

//Randomly generation of parameters of tasks

fprintf(stderr,"before:\n");
    for (i=0;i<nT;i++){
            fprintf(stderr,"%d;%d;%d;%d\n", tasks[i].ident, tasks[i].computation, tasks[i].deadline,tasks[i].period);
        }

size_t size = sizeof(tasks) / sizeof(task_t*);

qsort(tasks, size, sizeof(task_t *), compare);


    fprintf(stderr,"\after:\n");
    for (i=0;i<nT;i++){
            fprintf(stderr,"%d;%d;%d;%d\n", tasks[i].ident, tasks[i].computation, tasks[i].deadline,tasks[i].period);
        }

Before and after qsort, the result is the same.在qsort之前和之后,结果是一样的。 I think the problem is the pointer but I don't know how to solve it.我认为问题是指针,但我不知道如何解决。 I have tried a lot of combinations qsort(&tasks, size, sizeof(task_t *), &compare);我尝试了很多组合 qsort(&tasks, size, sizeof(task_t *), &compare); and also inside compare function, but the result does not change.并且也在比较函数中,但结果不会改变。 Could you help me?你可以帮帮我吗? Sorry if the question is so many repeated.对不起,如果问题重复了这么多。

size_t size = sizeof(tasks) / sizeof(task_t*);

only works if tasks is an array of task_t* .仅当taskstask_t*数组task_t* It isn't, it's a pointer to task_t (presumably to an array of task_t , but not one with compile-time size).不是的话,它是一个指向task_t (据推测的阵列task_t ,却没有一个编译时的大小)。 You can't use sizeof in that case, you just have to know how big the array is in some other way.在这种情况下您不能使用sizeof ,您只需要以其他方式知道数组有多大。 As is, you basically asked qsort to sort an array with one element in it. qsort ,您基本上要求qsort对包含一个元素的数组进行排序。

You've also written your comparator wrong;你的比较器也写错了; if the array is of task_t s, then the void* s it receives are really pointers to task_t , not double pointers to task_t .如果数组是task_t s,那么它接收的void* s 实际上是指向task_t指针,而不是指向task_t双指针。 So you'll need to change:所以你需要改变:

    task_t *ia = *(task_t**)a;
    task_t *ib = *(task_t**)b;

to:到:

    const task_t *ia = a;
    const task_t *ib = b;

Lastly, you need to pass sizeof(task_t) to qsort , not sizeof(task_t *) ;最后,您需要将sizeof(task_t)传递给qsort ,而不是sizeof(task_t *) again, the array is of task_t , not task_t* .同样,数组是task_t ,而不是task_t*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM