简体   繁体   English

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

[英]C++ Deleting two dimensional dynamically allocated array

I have a problem with two dimensional dynamically allocated array I'm using in my code. 我在代码中使用的二维动态分配数组存在问题。 Everything works fine until my program tries to call the destructor of my tablica2D object. 一切正常,直到我的程序尝试调用tablica2D对象的析构函数。 I get a runtime error "HEAP CORRUPTION DETECTED" when my program gets to the last delete[] tab command. 当程序进入最后的delete[] tab命令时,出现运行时错误“ HEAP CORRUPTION DETECTED”。 Does this mean that the loop preceding it already deallocates all of memory assigned to tab ? 这是否意味着在它之前的循环已经释放了分配给tab所有内存? I was under the impression that to deallocate all of dynamically assigned memory there needs to be one delete command for each new command. 我的印象是,要释放所有动态分配的内存,每个new命令都需要一个delete命令。 Or is something else causing this error? 还是其他原因导致此错误?

Here is the code of the class that's causing me trouble: 这是引起我麻烦的类的代码:

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

You are using the wrong variable in your new loop, and additionally creating a 3d array instead of a 2d array: 您在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]
    }

vs: vs:

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

If I need a C-like 2D array I always use: 如果我需要类似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;
}

For usage: 使用方法:

myarr[x][y]

Then for freeing: 然后释放:

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

The same, with some little effort, can be applied for N-dimentional array. 只需付出一点点努力,就可以将其应用于N维数组。

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

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