我想使用二维指针制作矩阵。
当我使用“malloc”和“free”函数来使用内存时没有问题(请参阅我的代码)。
但是,我无法使用“new”和“delete”编写相同的代码。
如您所知,一维指针可以通过“new”声明。例如,
double *example = new double [10];
delete [] example;
那么,如何使用“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);
好吧,直接等价的是这样的:
// 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;
确实,不过,你不想要这个。它完全是一团糟,并且没有内存位置。
更不用说手动内存管理是完全容易出错的,这一点可以通过以下事实来证明:row
double
s 在你的原始代码中。
这是怎么回事:
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;
};
It uses vector
避免any那种令人讨厌的内存管理,并将 2D 索引访问包装在实际上是单个数据缓冲区的地方,这样您就不需要n指针间接。
您可以根据需要将布局调整为行优先或列优先。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)