In article
<0e494561-cbb9-4949-9e29->,
Chad <> wrote:
> At the following url http://c-faq.com/lib/qsort2.html, they have the
> following
>
> Q: Now I'm trying to sort an array of structures with qsort. My
> comparison function takes pointers to structures, but the compiler
> complains that the function is of the wrong type for qsort. How can I
> cast the function pointer to shut off the warning?
>
> A: The conversions must be in the comparison function, which must be
> declared as accepting ``generic pointers'' (const void *) as discussed
> in question 13.8 above. For a hypothetical little date structure
>
> struct mystruct {
> int year, month, day;
> };
>
> the comparison function might look like [footnote]
>
> int mystructcmp(const void *p1, const void *p2)
> {
> const struct mystruct *sp1 = p1;
> const struct mystruct *sp2 = p2;
> if(sp1->year < sp2->year) return -1;
> else if(sp1->year > sp2->year) return 1;
> else if(sp1->month < sp2->month) return -1;
> else if(sp1->month > sp2->month) return 1;
> else if(sp1->day < sp2->day) return -1;
> else if(sp1->day > sp2->day) return 1;
> else return 0;
> }
>
> (The conversions from generic pointers to struct mystruct pointers
> happen in the initializations sp1 = p1 and sp2 = p2; the compiler
> performs the conversions implicitly since p1 and p2 are void
> pointers.)
>
> The question is, why don't you use something like
>
> const struct mystruct *sp1 = &p1;
> const struct mystruct *sp2 = &p2;
Because:
&p1 == the address of the variable (parameter, actually) p1
p1 == the variable holding the address of the struct under comparison
*p1 == the struct under comparison
Assuming p1 contains the (randomly chosen) address 5, and assuming p1 is
located in memory at (randomly chosen) location 27, and that the "..."
is replaced by the "const struct mystruct *" as shown above, the
following would be true:
assignment result
....sp1 = &p1 sp now holds 27 (the address of p1)
....sp1 = p1 sp now holds 5 (the contents of p1)
....sp1 = *p1 sp now holds <whatever value is found at location 5>
BUT...
Since p1 is a function parameter, rather than an actual variable, I
believe trying to take its address will result in undefined behavior.
(unless special steps are taken to make things happen differently,
parameters are usually passed on the stack, which makes taking their
address either impossible, or pointless, because for practical purposes,
they don't really HAVE an address to take.)
--
Don Bruder -
- If your "From:" address isn't on my whitelist,
or the subject of the message doesn't contain the exact text "PopperAndShadow"
somewhere, any message sent to this address will go in the garbage without my
ever knowing it arrived. Sorry... <http://www.sonic.net/~dakidd> for more info