0
    qsort(words, size1, size2, compareWords);

inside compare words:

    int compareWords(const void *ac, const void *bc)

this works:

    char const *a = *(const char **)ac;

these don't (a gets some garbage values):

    char const *a = ac;
    char const *a = (const char *) ac;

what is the rationale?

Also, in some examples I see size2 to be sizeof(char *). Shouldn't this be sizeof(*words)?

words is declared as: char *words[] = {"abc", "pqr", "abcd", "pqsl"};

4
  • You must show the declaration of words, since you're asking questions about how to access it. Commented Aug 23, 2013 at 10:23
  • You're right, size2 is the size of one element. So, size2 = sizeof(*words) or better size2 = sizeof(char). Commented Aug 23, 2013 at 12:10
  • @Michael is sizeof(* words) = sizeof(char)?? In my example words array, sizeof(* words) comes out to be 4 whereas sizeof(char) = 1. I don't think they are the same. Commented Aug 23, 2013 at 20:26
  • @Sushil, yes my bad... *words is a char* so yeah sizeof(char*) is the same as sizeof(*words) Commented Aug 24, 2013 at 16:17

1 Answer 1

3

When qsorting an array of T, your comparison function must convert its const void* pointers to const T*, because T can't be taken by value.

If words is an array of char* or char const *, you have to convert the arguments to char* const * or char const * const * respectively, it's natural when said this way.

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

2 Comments

hey, thx, but to be precise I wanted to know whats with *(const char **)ac - seems pretty un-intuitive to me... what is wrong in typecasting with (const char*)?
You have an array of char*, and the comparison function always receives pointers to elements in the array. Therefore, pointers to char*. These pointers also happen to be const, so *(const char **)ac is not const-correct, though there are no actual consequences since you don't try to write to this pointer.

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.