Created
May 1, 2014 08:32
-
-
Save youyongsong/2f6fc941e9e7ec41a9d8 to your computer and use it in GitHub Desktop.
C与C++的动态多维数组的建立与释放
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//二维动态数组的分配与释放 | |
//语言: 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); | |
/*-------------------------------------------*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment