如何使用"new"而不是"malloc"动态分配2D数组? [英] How to use 'new' instead of 'malloc' to allocate a 2D-array, dynamically?
问题描述
我想使用2D指针制作矩阵.
I'd like to make matrix using 2-D pointer.
当我将'malloc'和'free'函数用于内存使用时,没有问题(请参阅我的代码). 但是,我无法使用'new'和'delete'编写相同的代码.
There was no problem when I used 'malloc' and 'free' functions for memory use (see my code). However, I couldn't write the same code using 'new' and 'delete'.
您知道,一维指针可以由'new'声明.例如,
As you know, 1-D pointer can be declared by 'new'. For example,
double *example = new double [10];
delete [] example;
然后,如何使用'new'声明二维指针?
Then, how can I declare 2-D pointer using 'new'?
double **matrix; // 2-D pointer which represents entries of a matrix
int row, column; // the number of rows and column of the matrix
int i;
// set the size of the matrix
row = 3;
column = 5;
// allocate memories related to the number of rows
matrix = (double **)malloc(sizeof(double *) * row);
// allocate memories related to the number of columns of each row
for(i = 0; i < row; i++)
{
matrix[i] = (double (*))malloc(sizeof(double) * column);
}
// example: use of matrix
matrix[2][4] = 10.5;
// return used memories
free(matrix);
推荐答案
嗯,直接等效项是这样的:
Well, the direct equivalent is like this:
// allocate memories related to the number of rows
double** matrix = new double*[row];
// allocate memories related to the number of columns of each row
for(i = 0; i < row; i++)
{
matrix[i] = new double[column];
}
// usage here
// de-allocate memories related to the number of columns of each row
// (YOU FORGOT THIS IN YOUR ORIGINAL CODE!!!)
for(i = 0; i < row; i++)
{
delete matrix[i];
}
delete[] matrix;
确实,您不想要这个.这完全是一团糟,并且没有本地内存.
Really, though, you don't want this. It's a complete mess and has like no memory locality.
更不用说手动存储管理完全容易出错了,这可以从原始代码中泄漏row
double
s的事实得到证明.
Not to mention all that manual memory management is totally error-prone, as evidenced by the fact that you have a leak of row
double
s in your original code.
这是怎么回事:
struct Matrix
{
Matrix(const unsigned int row, const unsigned int column)
: row(row)
, column(column)
, data(row*column, 0)
{}
double& at(const unsigned int y, const unsigned int x)
{
return data[y + x*row];
}
private:
const unsigned int row, column;
std::vector<double> data;
};
它使用vector
来避免任何那种讨厌的内存管理,并且将2D索引访问包装在实际上是单个数据缓冲区的周围,从而使您没有 n 指针间接.
It uses vector
to avoid any of that nasty memory management, and wraps 2D index access around what's actually a single data buffer so that you don't have n pointer indirections.
您可以根据需要将布局调整为以行为主或以列为主.
You can adjust the layout to be row-major or column-major depending on your needs.
这篇关于如何使用"new"而不是"malloc"动态分配2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!