player_t* getFirstMatch(player_t** sortedPlayers, int playerCount, char* inputString)
{
player_t searchPlayer;
player_t* searchPlayerPointer = &searchPlayer;
searchPlayer.nameLast = inputString;
searchPlayerPointer = (player_t*) bsearch(searchPlayerPointer,
*sortedPlayers, playerCount, sizeof(player_t*),
playerCompareLast);
return searchPlayerPointer;
}
My program gets a segmentation fault on the line that uses bsearch(). What am I doing wrong here? Here is my comparison function. I was using a similar version for qsort, but now I need to use this one for bsearch :
int playerCompareLast(const void *p1, const void *p2)
{
char* nameLast1;
char* nameLast2;
int result;
nameLast1 = (*(player_t **)p1)->nameLast;
nameLast2 = (*(player_t **)p2)->nameLast;
result = strcmp(nameLast1, nameLast2);
return result;
}
The player_t type is just a Struct with a bunch of different members (like nameLast, nameFirst, etc.). I can't figure out what is wrong with my bsearch() arguments!
You are trying to use
bsearch
to search an array of pointers, apparently: thebase
argument isplayer_t**
and thesize
argument issizeof(player_t*)
. The implementation ofplayerCompare
seems to match this, as it castsp
toplayer_t**
.Alas, you are passing the key as
player_t*
, not asplayer_t**
. To match the behavior ofplayerCompare
your should pass&playerPointer
(that is ,player_t**
).I expect the access violation/seg fault to occur in
playerCompare
called bybsearch
(includingstrcmp
called fromplayerCompare
), a quick inspection of the dump or a look in the debugger at the stack raising it should confirm.