In compare_names()
, you are inappropriately dereferencing the arguments after the cast. The types for the local variables are type char **
, but you are casting the arguments as char **
and dereferencing that results in a char *
.
namea
and nameb
are pointers to the elements of your array names[]
declared in main()
. That means, their types are actually pointer to char *
. When you dereferenced these arguments but assigned them to a char **
, you cause the local variable to treat the char *
as a char **
(your compiler should have issued a diagnostic warning you about this problem). Now, you take a pointer value that is a char *
, and dereference it when you pass it to strcmp()
. This causes the program to treat sizeof(char *)
bytes of the string as a pointer value for the strcmp()
function. Since 4 or 8 (or whatever sizeof(char *)
is) bytes consisting of printable characters reinterpreted as a pointer value rarely yields a valid pointer, when strcmp()
tries to use those pointers, a segmentation fault occurs.
One possible fix is to not dereference when you initialize your local variables. However, the arguments are const void *
, so you can avoid the cast altogether if you declare your local variables to be a pointer to a const
type:
int compare_names(const void* namea, const void* nameb){
char* const * a = namea;
char* const * b = nameb;
return strcmp(*a,*b);
}
Note that your implementation of compare_scores_desc()
fails if a - b
results in signed integer overflow. For example, if a
is INT_MAX
and b
is -1
. You should fix your implementation to work for all cases.
int compare_scores_desc(const void* scorea, const void* scoreb){
const int *a = scorea;
const int *b = scoreb;
return (*a > *b) - (*a < *b);
}