1

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

4
  • point* ptarr[2]={pt1,pt3} - how did this even compile? Commented Feb 5, 2013 at 6:57
  • point* ptarr[2]={pt1,pt3} //pt1 and pt3 have type point Does that actually work ? Commented Feb 5, 2013 at 6:57
  • Sorry i made a typo. pt1 and pt3 are actually point* Commented Feb 5, 2013 at 7:02
  • When in doubt, add parenthesis. Commented Feb 5, 2013 at 9:21

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.