3
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;
}

我的程序在使用 bsearch() 的行上出现分段错误。我在这里做错了什么?这是我的比较功能。我在 qsort 中使用了类似的版本,但现在我需要在 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; 
}

player_t 类型只是一个包含一堆不同成员(如 nameLast、nameFirst 等)的 Struct。我无法弄清楚我的 bsearch() 参数有什么问题!

4

1 回答 1

3

You are trying to use bsearch to search an array of pointers, apparently: the base argument is player_t** and the size argument is sizeof(player_t*). The implementation of playerCompare seems to match this, as it casts p to player_t**.

Alas, you are passing the key as player_t*, not as player_t**. To match the behavior of playerCompare your should pass &playerPointer (that is , player_t**).

I expect the access violation/seg fault to occur in playerCompare called by bsearch (including strcmp called from playerCompare), a quick inspection of the dump or a look in the debugger at the stack raising it should confirm.

于 2013-12-15T21:39:32.263 回答