When the memory is requested, the rows are allocated first, and then the columns are allocated;
void Malloc2darray (int **parr, int x, int y) { int i; PARR = (int * *) malloc (x * sizeof (int *)); if (!parr) { printf ("Dynamic request memory failed!") \ n "); return NULL; } for (i = 0; i < x; i + +) { parr[i] = (int *) malloc (y * sizeof (int)); if (!parr[i]) { printf ("Dynamic request memory failed!") \ n "); return NULL;}} }
When the memory is freed, the column is released first, and then the row is released;
void Free2darray (int **parr, int x, int y) { int i; for (i = 0; i < x; i + +) {free (parr[i]); Parr[i] = NULL; } Free (PARR);
However, the problem with this is that allocating memory is not contiguous and there is a problem with the whole block of memory operations.
The following code allocates memory that is contiguous
void Malloc2darray2 (int **parr, int x, int y) { int i; PARR = (int * *) malloc (x * sizeof (int *)); if (!parr) { printf ("Dynamic request memory failed!") \ n "); return NULL; } PARR[0] = (int *) malloc (x * y * sizeof (int)); if (!parr[0]) { printf ("Dynamic request memory failed!") \ n "); Free (PARR); return NULL; } for (i = 0; i < x; i + +) parr[i] = parr[i-1] + y;//index associated with the corresponding data address memset (p[0], 0, nheight * nwidth);//two-dimensional array clear 0}v OID free2darray2 (int **parr, int x, int y) {free (parr[0]); Parr[0] = NULL; Free (PARR);
Reference Http://03071344.lofter.com/post/10871e_34cade
Dynamic memory allocation for two-dimensional arrays