错误:在C ++中取消分配2D数组

时间:2015-02-05 05:21:30

标签: c++ arrays visual-c++

创建了一个MCVE。

当我尝试在ConnectNGame类中释放2D数组时出错。

以下是Source.cpp的代码

#include <iostream>
#include "ConnectNGame.h"
using namespace std;

int main()
    {
        int connect = 3;
        ConnectNGame game(connect);
        game.~ConnectNGame();
        return 0;
    }

ConnectNGame.h中的代码

#ifndef CONNECTNGAME_H
#define CONNECTNGAME_H

struct Position
{
    int row, col;
};

class ConnectNGame
{
private:
public:
    int rows;
    int cols;
    char** gameBoard;
    ConnectNGame();
    ConnectNGame(int);
    ~ConnectNGame();
};
#endif

和ConnectNGame.cpp

#include <iostream>
#include "ConnectNGame.h"
using namespace std;

ConnectNGame::ConnectNGame()
{
    rows = 0;
    cols = 0;
}

ConnectNGame::ConnectNGame(int pieces)
{
    rows = pieces + 2;
    cols = pieces + 3;
    gameBoard = new char*[rows];
    for (int count = 0; count < rows; count++)
    {
        gameBoard[count] = new char[cols];
        for (int count2 = 0; count2 < cols; count2++){
            gameBoard[count][count2] = ' ';
        }
    }
}
ConnectNGame::~ConnectNGame()
{

    for (int i = 0; i < rows; i++) {
        delete[] gameBoard[i];
    }
    delete[] gameBoard;
}

调用析构函数时,程序崩溃。我不知道为什么会这样,任何帮助都会受到赞赏。

0 个答案:

没有答案