Link to home
Start Free TrialLog in
Avatar of chsalvia
chsalvia

asked on

casting with strcmp sort function

Demonstrations of qsort which sort an array alphabetically usually define a sort function like this:

int compare(const void* A, const void* B) {
      return( strcmp(*((char **)A), *((char **)B) ) );
}

Why is there a need to cast to char**, and then derefence to get a char* ?  Why not just cast to char* ?

I tried:

int compare(const void* A, const void* B) {
      return( strcmp((char *)A), (char *)B) ) );
}

This doesn't sort properly.  But I can't see the difference between the two functions.  Can someone explain why casting to char** and then dereferencing is functionally different than simply casting to char* ?
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It's easier if you make a drawing of the above example, showing the pointers etc.
And about that compare function, you'd have to call it like this :

    int compare(const void* A, const void* B) {
         return( strcmp(*((char **)A), *((char **)B) ) );
    }

    char *strA = "stringA";
    char *strB = "stringB";
    compare(&strA, &strB);

Is that how it's done ?

If you want to use your compare function, you'd call it like this :

    int compare(const void* A, const void* B) {
         return( strcmp((char *)A, (char *)B ) );
    }

    char *strA = "stringA";
    char *strB = "stringB";
    compare(strA, strB);
Avatar of chsalvia
chsalvia

ASKER

>> And about that compare function, you'd have to call it like this :

Well, I wouldn't call it directly.  It is just meant to be passed to qsort.  I found the function in a qsort tutorial, in fact.

But I understand what you're saying about the different pointer locations.  Thank you.