简体   繁体   中英

Deleting char matrix

I'm having trouble deleting a char matrix , I'm using visual studio and I'm getting an error once the code reaches this line :

delete[] AlloBoard[i];

this is the full code:

#include <iostream>
using namespace std;
char** buildMat(int h, int w)
{
    char**mat;
    mat = new char*[w];
    for (int i = 0; i < w; i++)
        mat[i] = new char[h];
    return mat;
}
int main()
{
    char** AlloBoard=buildMat(4,5);
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            AlloBoard[i][j] = 'x';
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 5; j++)
            cout << AlloBoard[i][j];
        cout << endl;
    }
     for (int i = 0; i < 5; i++)
        delete[] AlloBoard[i];
            delete[] AlloBoard;

            cout << "DONE" << endl;
}

appreciate the help!

You initially create 5 arrays of 4 chars each, but then you treat it like 4 arrays of 5 chars each. If your intent is to have matrix like this:

xxxxx
xxxxx
xxxxx
xxxxx

You need to change

buildMat(4,5);

to

buildMat(5,4);

And when deleting, do the loop to 4 not 5

for (int i = 0; i < 4; i++)
    delete[] AlloBoard[i];
        delete[] AlloBoard;

https://ideone.com/4cgCt3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM