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

时间:2015-04-05 16:04:46

标签: c++ arrays dynamic-allocation

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

以下是给我带来麻烦的课程代码:

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;
    }
};

2 个答案:

答案 0 :(得分:2)

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

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

VS

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

答案 1 :(得分:0)

如果我需要类似C的2D数组,我总是使用:

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维数组。

相关问题