We help IT Professionals succeed at work.

# How to free a dynamically allocated multidimensional array??

on
Medium Priority
328 Views
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??
Comment
Watch Question

## View Solution Only

Commented:
free(array2[0]);
free(array2);

Looking at it quickly, it appears to work but I think its uncoventional...

When allocating a multidimensional array, just doing 1 malloc is fine (i.e. rows * columns * size).
Or allocating a vector of row points and allocating each row independently...

The allocates a row vector and fills in each row one at a time into an array....maybe there's a reason
you want to do it this way....

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Hi leisner,

http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_21787694.html

It is an effective method that has its advantages.

Paul

Commented:
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

Commented:
for (int i = 0; i < nrows; i++) {
free(array2[i]);
}
free(array2);

Commented:
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*NCOL*sizeof(int));

this can be delete as free(arr);

Commented:
>>int (* arr)[NCOL] = (int (*)[NCOL])malloc(NROWS*NCOL*sizeof(int));
Nice! I've never seen that technique before!

Paul
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile