C++删除二维动态分配数组

C++ Deleting two dimensional dynamically allocated array

我在代码中使用的二维动态分配数组有问题。一切正常,直到我的程序尝试调用 tablica2D 对象的析构函数。当我的程序执行到最后一个 delete[] tab 命令时,出现运行时错误 "HEAP CORRUPTION DETECTED"。这是否意味着它之前的循环已经释放分配给 tab 的所有内存?我的印象是,要释放所有动态分配的内存,每个 new 命令需要一个 delete 命令。还是其他原因导致此错误?

这是给我带来麻烦的 class 的代码:

class tablica2D
{
    static const int k = 2;
    int n, m;
    string **tab;
public:
    tablica2D(int n, int m)
    {
        this->n = n;
        this->m = m;

        tab = new string*[n];
        for (int i = 0; i < m; i++)
        {
            tab[i] = new string[m];
        }
    }
    string* operator [](int n)
    {
        return tab[n];
    }
    static const bool compareRows(const string* i, const string* j)
    {
        int x = atoi(i[k].c_str());
        int y = atoi(j[k].c_str());
        return x > y;
    }
    void sort()
    {
        std::sort(tab, tab + n, compareRows);
    }
    ~tablica2D()
    {
        for (int i = 0; i < n; i++)
        {
            delete[] tab[i];
        }
        delete[] tab;
    }
};

您在 new 循环中使用了错误的变量,并且另外创建了一个 3d 数组而不是 2d 数组:

    for (int i = 0; i < m; i++)
    //                 ^^, should be n
    {
        tab[i] = new string[m];
        //                 ^^^
        // should be new string, not new string[m]
    }

对比:

    for (int i = 0; i < n; i++)
    //                 ^^, this one is correct
    {
        delete[] tab[i];
    }

如果我需要一个类似 C 的二维数组,我总是使用:

type **myarr = new type*[X];
myarr[0] = new type[X*Y];
for (int i = 1; i < X; i++) {
    myarr[i] = myarr[0] + i * Y;
}

用法:

myarr[x][y]

然后释放:

delete[] myarr[0];
delete[] myarr;

同理,稍加努力,也可以应用于N维数组。