youyongsong
5/1/2014 - 8:32 AM

C与C++的动态多维数组的建立与释放

C与C++的动态多维数组的建立与释放

//二维动态数组的分配与释放
//语言: C & C++
/*-------------------------------------------*/
int row, col;
int **mat;

//C
mat = (int**) malloc(row * sizeof(int *));
for(int i = 0; i < row; i++)
  mat[i] = (int*) malloc(col * sizeof(int));

for(int i = 0; i < row; i++)
  free((void*) mat[i]);
free((void*) mat);

//C++
mat = new (int*)[row];
for(int i = 0; i < row; i++)
  mat[i] = new int[col];

for(int i = 0; i < row; i++)
  delete mat[i];
delete []mat;
/*-------------------------------------------*/
  
//三维数组的分配与释放
//语言:C
/*-------------------------------------------*/
int m, n, p;
int ***triArray;
  
triArray = (int ***) malloc(m * sizeof(int **));
for(int i = 0; i < m; i++)
  triArray[i] = (int **) malloc(n * sizeof(int *));
for(int i = 0; i < m; i++){
  for(int j = 0; j < n; j++)
    triArray[i][j] = (int *) malloc(p * sizeof(int)); 
}
  
for(int i = 0; i < m; i++){
  for(int j = 0; j < n; j++)
    free((void*) triArray[i][j]);
}
for(int i = 0; i < m; i++)
  free((void*) triArray[i]);
free((void*) triArray);
/*-------------------------------------------*/