释放这个特定的2d阵列的内存

时间:2017-07-14 17:49:23

标签: c++ pointers memory-management

我目前正在使用特定的API,因此我必须使用原始指针,但是考虑到指针的特定排列,我不确定如何最好地清除内存并避免任何未定义的行为。这样做。

double *data1 = new double[rows*columns];
double **data2 = new double*[rows];
data2[0] = data1;  // Point to first row

for (int i = 1; i < columns; i++) {
    data2[i] = data2[i - 1] + rows;
}

我尝过类似下面的内容,但我认为没错。

for(int i = 0; i < rows; i++) {
    delete [] data2[i];
}
delete [] data2;
delete [] data1;

1 个答案:

答案 0 :(得分:0)

谁拥有什么?

这个问题将决定你如何删除对象。

我认为您正在做的是创建一个大型数组来保存二维数据数组,然后创建另一个数组来保存指向每行开头的指针。

这是两个新闻,因此有两个删除。

像这样可视化可能更容易:

struct matrix_view
{
    int rows, columns;

    // this pointer owns a block of doubles
    double* entire_buffer = nullptr;

    // this pointer owns a block of pointers, but not the memory
    // they point to
    double** row_pointers = nullptr;
};

matrix_view create_matrix(int rows, int columns)
{
    auto result = matrix_view{ rows, columns, nullptr, nullptr };

    auto size = rows * columns;
    result.entire_buffer = new double [size];
    result.row_pointers = new double* [rows];
    auto first = result.entire_buffer;
    auto last = first + size;
    auto dest = result.row_pointers;
    while (first != last) {
        *dest++ = first;
        first += columns;
    }
    return result;
}

void destroy_matrix(matrix_view m)
{
    // always destroy in reverse order

    delete [] m.row_pointers;
    delete [] m.entire_buffer;
}