Reputation: 9996
The below program sorts all the suffices of a string using qsort()
library function.
int sacomp(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b); <------------
}
void sort(string s)
{
int size = s.size();
char const *data = s.c_str();
char const **sa = new char const *[size+1];
for(int i = 0; i < size; i++)
sa[i] = data+i;
qsort(sa, size, sizeof(sa[0]), sacomp); // O(n * Lon n)
}
int main()
{
string s("ABCCCDEFABBABBA");
sort(s);
return 0;
}
I am not able to understand the casting done in the sacomp()
method.
strcmp(*(const char**)a, *(const char**)b);
Why a is casted to const char** and then being de-referenced?
Upvotes: 1
Views: 172
Reputation: 12865
Your element is char *
, therefore you should change void on char *
and get pointer to char *
, which is char **
. Meanwhile strcmp needs char *
.
Upvotes: 0
Reputation: 1105
qsort passes pointer of elements. You passed sa as char**
, so every element is char*
, and qsort passes char**
, finally you got char**
in the sort function.
Upvotes: 1