简体   繁体   中英

Qsort array of strings in descending order

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?

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);
}

只需返回否定结果( -strcmp(*pp, *qq) )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM