qsort
Its pretty rare for me to post questions here but I came across this one about qsort I can't answer. If I try to sort an array of character strings such as char array[255][20] qsort works ok as expected. But if I declare the array like this qsort fails: char*array[255]
// this is ok
char array[255][20];
int NumStrings = 0;
// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);
or
// this fails
char* array[255]= {0};
int NumStrings = 0;
// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
You have to change the signature of the compare function, to expect pointers to two character pointers, not pointers to two character arrays.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
Thanks, it works now :)
Below is for readers who may not realize what the solution was.
#include <stdio.h>
int compare(const void *a, const void *b)
{
const char* a1 = *(const char**)a;
const char* b1 = *(const char**)b;
return strcmp(a1,b1);
}
int main()
{
int c = 0;
char* _array[] = {"now ","is ","the ","time","for ","all ","good"};
c = sizeof(_array)/sizeof(_array[0]);
qsort(_array,c, sizeof(char*),compare);
cout << "\n\nThe alphabetized words are:\n";
for (int i = 0; i < c; i++)
{
cout << _array [i] << "\n";
}
cin.get();
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343