I am trying to figure out how to use qsort with an array of strings. My code looks like this.
char words[500][256];
int numOfWords; // this is calculated above
int sortWordList() {
int length = sizeof(words) / sizeof(char *);
qsort(words, length, sizeof(char*), compare);
}
int compare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa,pb);
}
However, I get a "Access violation reading location 0x###.." everytime and I dont know whats wrong. Can anyone spot my problem?
EDIT: Thanks for the wonderful help. You guys are always the best.
You are not casting your const void *
to const char *
properly, to do so, use instead:
const char *pa = (const char *)a;
const char *pb = (const char *)b;
Plus compare()
should be above sortWordList()
as you're using it in sortWordList()
.
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.