【发布时间】:2015-08-08 10:56:55
【问题描述】:
我想用二维指针制作矩阵。
当我使用 '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);
【问题讨论】:
-
@minitech:你在 cmets 中回答,mod? :(
标签: c++ pointers multidimensional-array malloc