【发布时间】:2016-06-11 16:15:33
【问题描述】:
我在头文件中创建了两个结构,一个用于卡片,一个用于手,如下所示:
struct Card
{
char *face; // define pointer face
char *suit; // define pointer suit
};
struct Hand
{
struct Card *cards[15]; // define an array to hold a card
char hand[13]; // defines the type of hand
};
在我的printHand 函数中,我尝试为每手牌添加一张牌,然后将这些手牌添加到代表所有玩家的数组中。我运行了一个调试器,这里出现了分段错误:
// Here we will add the cards to the array holding the player's hands
totalHands[indexHand].cards[indexCard]->face = shuffledDeck[indexCard].face;
totalHands[indexHand].cards[indexCard]->suit = shuffledDeck[indexCard].suit;
调试器打印EXC_BAD_ACCESS。这是我的功能:
void printHand(struct Card* shuffledDeck, char* argv[])
{
// total number of cards
const int DeckMaxSize = 53;
// get the command line input
int numOfHands = atoi(argv[1]);
int numOfCards = atoi(argv[2]);
// counters for our loops
int indexHand;
int indexCard;
struct Hand totalHands[10]; // an array holding all the hands
// allocate memory for our struct
struct Hand* tempHand = (struct Hand*)malloc(numOfCards * sizeof(struct Hand));
// Adjusted the command line arguments if the number cards/hand and
// players can not be resolved from a 52 sized deck
int validateInput = DeckMaxSize / numOfHands;
if (validateInput < numOfCards) {
numOfCards = validateInput;
printf("\n%s", "Input was adjusted to the size of the deck ( 52 )");
}
// Creates a new Hand and adds it to the totalHands[]
for (indexHand = 1; indexHand <= numOfHands; indexHand++) {
totalHands[indexHand] = *tempHand;
printf("\n\n%s %d\n", "Player : ", indexHand);
// add the cards to the hand and print each player's hand
for (indexCard = 1; indexCard <= numOfCards; indexCard++) {
// Here we will add the cards to the array holding the player's hands
totalHands[indexHand].cards[indexCard]->face = shuffledDeck[indexCard].face;
totalHands[indexHand].cards[indexCard]->suit = shuffledDeck[indexCard].suit;
// Print all of our player's hand
printf("\n%d %s ", indexCard, totalHands[indexHand].cards[indexCard]->face);
printf("%s", totalHands[indexHand].cards[indexCard]->suit);
}
// print a new line for formatting
printf("\n");
}
}
【问题讨论】: