我被要求制作一个2d动态数组,其大小等于M * M(用户输入),列和行的大小都是相同的M.
我的问题是在输入M和K值后,应用程序崩溃了。
我不完全理解构造函数和析构函数在动态数组中的使用,所以我认为那里有一些我不知道的东西。 任何帮助将非常感谢! :)
#include <iostream>
#include <iomanip>
#include <new>
#include <cmath>
using namespace std;
class Board {
private:
bool gameOver; //true if game is finished.
int K; // number of consecutive stones needed to win.
//int board [][];
int M;
int **ptr; // pointer to a pointer(**)
public:
Board();
~Board();
void getBoardSize();
void setArrayIndex();
void printBoard();
int getComputerInput();
int getPlayerInput();
void setIndexValue(int, int);
};
//Constructor to initiate variables.
Board::Board(){
gameOver = false;
M = 0;
K = 0;
//board [*M][*M];
ptr = new int*[M]; // create new array of pointers to int objects.
for (int i=0; i < M; i++){
ptr[i] = new int[M];
}
}
//The destructor to release the heap memory.
Board::~Board(){
for (int i=0;i<M; i++){
delete [] ptr[i];
}
delete[] ptr;
}
void Board::getBoardSize(){
cout << "Enter value for M ( > 2): " << endl;
cin >> M;
cout << "Enter value for K ( > 1): " << endl;
cin >> K;
}
void Board::setArrayIndex(){
for (int i=0; i < M; i++){
for (int j=0; j < M; j++){
ptr [i][j] = 0;
}
}
}
void Board::printBoard(){
for (int i=0; i < M; i++){
cout << setw(4) << i+1; //Print Column numbers first.
}
cout << endl; //column headers done...
for (int r=0; r < M; r++){
cout << setw(2) <<r+1 << " ";
for (int c=0; c < M; c++){
cout << ptr[r][c]; // index values printed.
if (c+1 < M){ //to prevent the last "---".
cout << "---";
}
}
cout << endl;
cout << setw(4);
for (int j=0; j < M; j++){
if (r+1 < M){ //to prevent the last "|".
cout << "|";
}
cout << " ";
}
cout << endl;
}
}
int Board::getComputerInput(){
int x, y;
cout << "PC: Input row and column (x, y) from 1 to M: " << endl;
cin >> x;
cin >> y;
cout << "PC Plays " << "(" << x << ", " << y << ")" << endl;
printBoard();
return x-1, y-1;
}
int Board::getPlayerInput(){
int x, y;
cout << "Human: Input row and column (x, y) from 1 to M: " << endl;
cin >> x;
cin >> y;
cout << "Human Plays " << "(" << x << ", " << y << ")" << endl;
printBoard();
return x-1, y-1;
}
void Board::setIndexValue(int a, int b){
//ptr [a][b] =
}
#endif /* NEWFILE_H */
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
Board object;
object.getBoardSize();
object.setArrayIndex();
object.printBoard();
//object.getComputerInput();
//object.getPlayerInput();
return 0;
}
答案 0 :(得分:0)
首先检查您是否没有为M
输入太大的值,因为如果没有足够的可用空间,这肯定会导致程序崩溃。
其次使用像 gdb 这样的调试器来运行程序。它也必须在Netbeans中可用。当应用程序崩溃时,它会指出崩溃的位置和故障类型。
您可以查看调用堆栈和变量值以查找崩溃的原因。