【发布时间】:2017-12-05 14:42:25
【问题描述】:
所以我在 c 中使用 qsort() 并且我的比较函数通常包括创建一个正确类型的指针并从参数中为其分配值。是否可以只从参数中转换指针而不创建新指针? 如果是这样,我做错了什么?
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;
}
我明白了:
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
编辑:
我用它编译了
int cmpfunc (struct date_t *one, struct date_t *two) {
return one->time - two->time;
}
但是,我将如何使用演员表呢?
【问题讨论】:
-
这样投射:
((struct date_t*)one)->time。注意运算符的优先级。 -
((struct date_t*)one)->time