Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
I am trying to sort an array of strings with qsort, using strcmp as the comparison function, but it is not working.
I am trying to sort an array of strings with qsort, using strcmp as the comparison function, but it is not working.
✍: Guest
By ``array of strings'' you probably mean ``array of pointers to char.'' The arguments to qsort's comparison function are pointers to the objects being sorted, in this case, pointers to pointers to char. strcmp, however, accepts simple pointers to char. Therefore, strcmp can't be used directly. Write an intermediate comparison function like this:
/* compare strings via pointers */
int pstrcmp(const void *p1, const void *p2)
{
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
The comparison function's arguments are expressed as ``generic pointers,'' const void *. They are converted back to what they ``really are'' (pointers to pointers to char) and dereferenced, yielding char *'s which can be passed to strcmp.
The call to qsort might look like
#include <stdlib.h>
char *strings[NSTRINGS];
int nstrings;
/* nstrings cells of strings[] are to be sorted */
qsort(strings, nstrings, sizeof(char *), pstrcmp);
2015-08-12, 1266👍, 0💬
Popular Posts:
How To Retrieve the Count of Updated Rows? - Oracle DBA FAQ - Working with Database Objects in PL/SQ...
Which is the best place to store ConnectionString in Dot Net Projects? I am about to deploy my first...
How do I debug thread ? This window is only seen when the program is running in debug mode. In windo...
Can one change the mouse pointer in Forms? The SET_APPLICATION_PROPERTY build-in in Oracle Forms all...
Are risk constant through out the project ? * Never say that risk is high through out the project. R...