我编写了以下代码,但无法弄清楚为什么我会遇到分段错误。
额外代码:
// A game keeps track of a Pack, and whether it should be shuffled, the score
// and how many points it takes to win, and the Players in the game
struct Game {
Pack pack; // Pack of cards
bool shuffle; // Shuffle the pack after each hand
int score[NUM_PARTNERSHIPS]; // Score for each partnership
int points_to_win; // Number of points to win the game
Player players[NUM_PLAYERS]; // Players in this game, in order around table
};
Player* Player_to_left(int playerindex, Game *game_ptr){
int index = (playerindex + 1)%4;
Player *player_ptr = &(game_ptr->players[index]);
return player_ptr;
}
static int Get_player_index(Player *player_ptr, Game *game_ptr){
Player *one_player = &(game_ptr->players[0]);
if(strcmp(player_ptr->name,one_player->name) == 0)
return 0;
Player *two_player = &(game_ptr->players[1]);
if(strcmp(player_ptr->name,two_player->name) == 0)
return 1;
Player *three_player = &(game_ptr->players[2]);
if(strcmp(player_ptr->name,three_player->name) == 0)
return 2;
Player *four_player = &(game_ptr->players[3]);
if(strcmp(player_ptr->name,four_player->name) == 0)
return 3;
return 0;
}
主要问题:
Player* Play_trick(Game *game_ptr, int leadindex, Player *lead_ptr, Suit trump){
Card cards[4] = {Player_lead_card(lead_ptr, trump)};
Card_print(cards); cout << " led by " << lead_ptr->name << endl;
int second = (leadindex + 1)%4;
Player *two_player = Player_to_left(leadindex, game_ptr);
cards[1] = Player_lead_card(two_player, trump);
if(second >= 0 && second <= 4)
Card_print(cards+1); cout << " led by " << two_player->name << endl;
int third = (second + 1)%4;
Player *third_player = Player_to_left(second, game_ptr);
cards[2] = Player_lead_card(third_player, trump);
if(third >= 0 && third <= 4)
Card_print(cards+2); cout << " led by " << third_player->name << endl;
int fourth = (third + 1)%4;
Player *fourth_player = Player_to_left(third, game_ptr);
cards[3] = Player_lead_card(fourth_player, trump);
if(fourth >= 0 && fourth <=4)
Card_print(cards+3); cout << " led by " << fourth_player->name << endl;
Card *highest = cards;
int itemp = 0;
for(int i = 1; i < 4; ++i){
if(Card_compare(cards, (cards + i), trump) < 0){
highest = (cards + i);
itemp = i;
}
}
if(itemp == 0){
cout << lead_ptr->name << " takes the trick" << endl;
return lead_ptr;
}
if(itemp == 1){
cout << two_player->name << " takes the trick" << endl;
return two_player;
}
if(itemp == 2){
cout << third_player->name << " takes the trick" << endl;
return third_player;
}
if(itemp == 3){
cout << fourth_player->name << " takes the trick" << endl;
return fourth_player;
}
return fourth_player;
}