2

To sort an array of strings in ascending order, I use:

int cmp(const void *p, const void *q) {
     char* const *pp = p;
     char* const *qq = q;
     return strcmp(*pp, *qq);
}

This will be then implemented into a qsort like so:

qsort(a, sizeof(a)(sizeof(a[0]), sizeof(a[0]), cmp);

How do you sort it in descending order?

2 Answers 2

7

One quick and easy way to do this is to multiply the result of strcmp() by -1 before returning it.

int cmp(const void *p, const void *q) {
     char* const *pp = p;
     char* const *qq = q;
     return -strcmp(*pp, *qq);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Welcome to Stack Overflow. -1 * strcmp(…) is a long-winded way of writing -strcmp(…). Another option is strcmp(*qq, *pp), reversing the order of the arguments.
Thanks Jon, that's an excellent observation! I've amended the answer.
3

Just return the negative result (-strcmp(*pp, *qq)).

1 Comment

Or use strcmp(*qq, *pp), reversing the order of the arguments.

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.