简体   繁体   English

删除字符矩阵

[英]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 : 我在删除char矩阵时遇到了麻烦,我在使用Visual Studio,并且一旦代码到达以下行,就会出现错误:

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. 最初,您创建5个数组,每个数组的4个字符,但随后将其视为4个数组,每个数组的5个字符。 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 而当删除时,循环到4而不是5

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

https://ideone.com/4cgCt3 https://ideone.com/4cgCt3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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