So I have a C function that goes like this:
int cmp (const void *a, const void* b)
return rot13cmp( (const char*)a, (const char*)b );
}
and rot13cmp is another function that takes two parameters of type const char *.
I pass this function into the compare parameter for the C qsort function but it doesn't seem to work.
However, if I instead cast the const void * variables by doing
return rot13cmp ( *(const char **)a, *(const char **)b );
the function then starts to work. I looked this up at SO but every source said that the first method of casting should work so I wanted to know why only the second one worked for me?
Edit: Here's the relevant code I have,
int cmp (const void *a, const void *b) {
return rot13cmp( (const char *)a, (const char *)b );
}
int rot13cmp (const char *a, const char *b) {
while (*a == *b && *a != '\n') {
a++;
b++;
}
if (*a == *b) { return 0; }
else if (*a == '\n') { return 1; }
else if (*b == '\n') { return 1; }
else { return rot13(*a) - rot13(*b);
}
and rot13 returns an int for the ASCII code of a letter rotated by 13 letters in the alphabet.
I called qsort by doing
qsort(words, word_count, sizeof(char*), cmp);
where words is an array of char** and word_count is an int. cmp is also just
qsort()
? – timraua
andb
have originally. From what you describe I'd guess they are pointers to pointers, but without information this is pure guessing. – Jens Gustedt