这是来自已经上交的家庭作业。该程序是一种纸牌游戏,可以正确播放,但在游戏结束时会出现分段错误。我可以将核心转储跟踪到我的delete [] playerArr,但是我认为真正的问题在于如何声明我的playerArr。
我的 .h 文件中有一个构造函数、复制、重载运算符和析构函数,可以很好地与其他程序配合使用,所以我认为我的问题出在主要问题上。我在这里和谷歌上查看了其他几个问题,但还没有找到像这样的问题。以下是代码片段:
struct Player
{
int currentHand; //current number of cards in given player's hand
Queue hand; //queue to store player's hand
};
在主要我分配了一个结构数组,我认为这是我的问题。我已经尝试过各种方法并犯了错误,但这个方法允许我的程序编译和我的游戏按设计运行:
//allocate array of Player structs
Player *playerArr = new Player[numPlayers];
for (int i = 1; i <= numPlayers; i++)
playerArr[i].currentHand = 0;
//enqueue playerArr.hand
deal(playerArr, deck, numPlayers, currentDeck);
这是我删除前清理的顺序,cout之后核心转储:
//exit do-while loop and end game
}
while (playerArr[currentPlayer - 1].currentHand != 0);
for (int i = 1; i < numPlayers; i++)
{
while (playerArr[i].currentHand > 0)
{
playerArr[i].hand.dequeue(catchQ);
playerArr[i].currentHand--;
}
}
//empty all deck/discard stacks
while (!deck.isEmpty())
deck.pop(catchPop);
while (!discard.isEmpty())
discard.pop(catchPop);
//reset hand/deck counters to defaults
catchQ = 0;
catchPop = 0;
currentDeck = 52;
currentPlayer = 1;
numPlayers = 2;
cout << "\n\n\n\t Good Game!" << endl << endl;
//free dynamic memory
delete [] playerArr;
我现在改变这个项目的成绩已经太晚了,在期末考试周我没有时间在办公时间拜访我的教授,所以如果有人为我提供解决方案,我可以从这个错误中吸取教训并继续前进。
谢谢
该问题的一个可能原因是您忘记了数组索引是从零开始的。
numPlayers
元素数组的索引从0
到numPlayers - 1
(包括)。
您展示的第一个循环不使用它,而是使用 if 从1
to numPlayers
,导致您将分配的内存索引到越界,从而导致未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句