简体   繁体   English

为qsort的比较转换结构的指针

[英]casting a pointer to struct for qsort's compare

So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. 所以我在c中使用qsort(),我的compare函数通常包括创建一个正确类型的指针并从参数中赋值。 is it possible to just cast the pointer from the arguments without creating a new one? 是否可以只从参数中转换指针而不创建新的指针? if so, what am i doing wrong? 如果是的话,我做错了什么?

struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}

i'm getting : 我越来越 :

main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union

EDIT: 编辑:

i got it to compile with 我得到它编译

int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}

but still, how would i do it with casts? 但是,我怎么会用演员阵容呢?

The type cast operator () has lower precedence than the pointer-to-member operator -> . 类型转换operator ()优先级低于指向成员的operator- -> So this: 所以这:

(struct date_t*)(one)->time

Is the same as this: 与此相同:

(struct date_t*)((one)->time)

You need to parenthesize what is casted, then you can dereference the pointer. 你需要用括号括起来,然后你可以取消引用指针。

int cmpfunc (const void * one, const void * two) {
    return ((const struct date_t*)(one))->time - ((const struct date_t*)two)->time;
}

Also note that the casted pointers are const to be consistent with the original pointers. 另请注意,转换指针是const与原始指针一致。

According to the handy precedence table , the cast operation has a lower precedence than the structure member access operator -> . 根据方便的优先级表 ,强制转换操作的优先级低于结构成员访问操作符-> So when doing (struct date_t*)(one)->time , first the member time is accessed (and failed, as one is a void* and has no such a member). 所以当做(struct date_t*)(one)->time ,首先访问成员time (并且失败,因为onevoid*并且没有这样的成员)。 And only then the cast is performed on the result. 然后才对结果执行演员表。 Instead you should force the precedence by using parentheses in appropriate places like: 相反,您应该通过在适当的位置使用括号来强制优先级,例如:

... ((struct date_t*)one)->time ...

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

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