Hristo
Hristo

Reputation: 46567

how to implement qsort in C

I need to implement qsort in C and sort in reverse lexicographical order. I'm confused on how to create and call the comparison function. This is what I have so far..

qsort (strArr, numLines, sizeof(char*) , sort);

int sort(const void * str1, const void * str2) {
 return (-1) * strcasecmp((char*) str1, (char*) str2);
};

Eclipse is telling me "'sort' undeclared (first use in this function)" on the qsort line, but I fear that's not my only problem. Any advice?

Thanks, Hristo

Revision... this is what my array looks like:

char **strArr = malloc(numLines * sizeof(char*));
fgets(output, 256, sourceFile);
strArr[i] = malloc(((int) strlen(output) + 1) * sizeof(char));
strcpy(strArr[i],output);

Upvotes: 2

Views: 2505

Answers (1)

user262976
user262976

Reputation: 2074

you would need to declare sort before using it:

int sort(const void * str1, const void * str2);

then the comparison might be:

return strcasecmp(*(char * const *)str2, *(char * const *)str1);

As @Chris Jester-Young points out you can swap the args to reverse the comparison.

the pointers have to be dereferenced...

Upvotes: 6

Related Questions