We help IT Professionals succeed at work.

How to free a dynamically allocated multidimensional array??

josabraham
josabraham asked
on
Medium Priority
328 Views
Last Modified: 2010-04-15
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

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.

Ask the Experts
Hi leisner,

Take a look at a discussion about this at:

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

It is an effective method that has its advantages.

Paul
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);
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);
>>int (* arr)[NCOL] = (int (*)[NCOL])malloc(NROWS*NCOL*sizeof(int));
Nice! I've never seen that technique before!

Paul
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

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

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.