本文同时发布在
二维数组动态空间的申请原则:
申请的时候从外层往里层,逐层申请;
释放的时候从里层往外层,逐层释放。
二维数组动态空间分配举例,首先来看一组使用new方法:
const size_t DIMENSION = 10;
int **pp = new int *[DIMENSION];
for (int i = 0; i < DIMENSION; ++i)
pp[i] = new int[DIMENSION];
pp[3][5] = 40;
for (int i = 0; i < DIMENSION; ++i)
delete pp[i];
delete pp;
|
还有一组使用malloc方法,简单需要存放30个double 数据的内存3*10:double **power;
int i,j;
power = (double **)malloc(sizeof(double) *3);
for(i =0; i< 3;i++)
{
power[i] = (double *)malloc(sizeof(double) * 10);
}
//....
for(i=0;i<3;i++)
{
free(power[i]);
}
free(power);
|
其实没有必要每次用for循环去分配内存。可以一次性申请所需要的内存: double **power;
double *subpower;
int i,j;
power = (double **)malloc(sizeof(double) *3);
subpower = (double *)malloc(sizeof(double) * 10 * 3);
for(i =0; i< 3;i++)
{
power[i] = &subpower[i * 10];
}
//...
free(subpower);
free(power);
|
阅读(5498) | 评论(0) | 转发(0) |