josabraham
asked on
How to free a dynamically allocated multidimensional array??
Hi I allocate the array2 in the following way.
int **array2 = malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;
How to free the allocated memory "array2" at the end??
int **array2 = malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;
How to free the allocated memory "array2" at the end??
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
int** i;
//Initialization
i=new int*[10]; //u can use malloc also
for(int index=0;index<10;index++)
i[index]=new int[10];
//Deletion
for(int index=0;index<10;index++)
delete [] i[index];
Regards
Prashant Sabnekar
//Initialization
i=new int*[10]; //u can use malloc also
for(int index=0;index<10;index++)
i[index]=new int[10];
//Deletion
for(int index=0;index<10;index++)
delete [] i[index];
Regards
Prashant Sabnekar
for (int i = 0; i < nrows; i++) {
free(array2[i]);
}
free(array2);
free(array2[i]);
}
free(array2);
To free the allocated memory you should use
free(array2[0]);
free(array2);
But a two dimensional can be declared as in a concise form
int (* arr)[NCOL] = (int (*)[NCOL])malloc(NROWS*NCO L*sizeof(i nt));
this can be delete as free(arr);
free(array2[0]);
free(array2);
But a two dimensional can be declared as in a concise form
int (* arr)[NCOL] = (int (*)[NCOL])malloc(NROWS*NCO
this can be delete as free(arr);
>>int (* arr)[NCOL] = (int (*)[NCOL])malloc(NROWS*NCO L*sizeof(i nt));
Nice! I've never seen that technique before!
Paul
Nice! I've never seen that technique before!
Paul
Take a look at a discussion about this at:
https://www.experts-exchange.com/questions/21787694/declare-define-a-two-D-array-dynamically-and-destroy-it-afere-using.html
It is an effective method that has its advantages.
Paul