Sup*_*ary 1 c++ malloc pointers multidimensional-array
我想用二维指针制作矩阵.
当我使用'malloc'和'free'函数进行内存使用时没有问题(参见我的代码).但是,我无法使用'new'和'delete'编写相同的代码.
如您所知,1-D指针可以通过'new'声明.例如,
double *example = new double [10];
delete [] example;
Run Code Online (Sandbox Code Playgroud)
那么,如何使用'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);
Run Code Online (Sandbox Code Playgroud)
嗯,直接等价是这样的:
// 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;
Run Code Online (Sandbox Code Playgroud)
但是,真的,你不想要这个.这是一个完整的混乱,并没有像没有记忆的地方.
更不用说手动内存管理完全容易出错,正如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;
};
Run Code Online (Sandbox Code Playgroud)
它用于vector避免任何讨厌的内存管理,并围绕实际上是单个数据缓冲区包装2D索引,这样就不会有n个指针间接.
您可以根据需要将布局调整为行主要或列主要.
| 归档时间: |
|
| 查看次数: |
3659 次 |
| 最近记录: |