C language multidimensional array memory allocation and release of malloc and free methods

  • 2020-04-01 23:32:32
  • OfStack

To allocate space to a two-dimensional array (m*n), the code can be written as follows:


char **a, i;
//I'm going to assign m pointer units, pointer units
//So the sizeof each cell is sizeof(char *).
a = (char **) malloc(m * sizeof(char * ));
//To allocate n character units,
//The m pointer cells above point to the first address of the n character cell
for(i = 0; i < m; i++)
a[i] = (char * )malloc(n * sizeof(char ));

Release should be:


int i;
for(i=0;i<m;i++)
    free((void *)a[i]);
free((void *)a);

If you allocate space for a 3d array (m*n*p), it should be:


char ***a, i, j;
a = (char ***) malloc(m * sizeof(char ** ));
for(i = 0; i < m; ++i)
    a[i] = (char **) malloc(n * sizeof(char * ));
for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
    a[i][j] = (char * )malloc(p * sizeof(char ));

The release code is the reverse process, and the specific code is:


int i,j,;
for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
        free((void *)a[i][j]);   
for(i = 0; i < m; ++i)
    free((void *)a[i]);
free((void *)a);

The allocation and release of multidimensional arrays above 3 d, the principle is the same as above.


Related articles: