Reputation: 3478
I'm trying to write a compare function for qsort and is having trouble with de-referencing double pointers.
I defined a structure
typedef struct {
float x;
float y;
} point;
and I made an array of pointers to point:
point* ptarr[2]={pt1,pt3} //pt1 and pt3 have type point*
My compare function is defined as follows:
int compare(const void * a, const void * b){
return *(point**)a->x-*(point**)b->x; //This is wrong
}
Since a and b are pointers to the values in the arrays, in my case they are pointers to pointers which point to struct point. Therefore I cast them into double pointer (point**), and then de-referenced it once, and tried to access the values inside struct. Compiler gave me a "request for member 'x' in something not a structure or union" error
I'm really confused about this. Can someone help me with it? thanks
Upvotes: 1
Views: 264
Reputation: 409482
If you check a reference table on operator precedence you will see that the ->
access operator has higher priority than typecasting. This means that the expression (point**)a->x
actually typecasts the x
member not the a
structure pointer. You want e.g. (*(point**)a)->x
.
Upvotes: 1
Reputation: 213837
It's just a syntax problem, really.
return *(point**)a->x-*(point**)b->x; // This is wrong
return (*(point**)a)->x - (*(point**)b)->x; // This is right
The reason you get an error because *x->y
is the same as *(x->y)
, but you want (*x)->y
.
Also you have a bug in your code:
point* ptarr[2]={pt1,pt3} // pt1 and pt3 have type point
Do you see the bug? Either pt1
and pt3
should have type point *
(in which case the comment is wrong), or pt1
and pt3
should be replaced by &pt1
and &pt3
. Errors in the comments should be treated as bugs, so it is a bug either way.
Upvotes: 1