我在头文件中创建了两个结构,一个用于卡片,另一个用于处理,如下所示:
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");
}
}发布于 2016-02-28 17:32:39
for(indexHand = 1; indexHand <= numOfHands; indexHand++){
...
for(indexCard = 1; indexCard <= numOfCards; indexCard++){ 这些循环从1到n(最大索引包括)。但是索引应该从0到n-1。因此,这些循环访问索引超出界限。
把你的循环修改成-
for(indexHand = 0; indexHand < numOfHands; indexHand++){
...
for(indexCard = 0; indexCard < numOfCards; indexCard++){ 编辑-
totalHands[indexHand].cards[indexCard]->face = shuffledDeck[indexCard].face;
totalHands[indexHand].cards[indexCard]->suit = shuffledDeck[indexCard].suit;在这两种语句之前,您不会为指针cards数组分配内存,但是您会取消引用它(未初始化的指针)。
分配此数组的内存指针,然后访问数组成员。
https://stackoverflow.com/questions/35685750
复制相似问题