Re: delete for 2D arrays
- From: "Doug Harrison [MVP]" <dsh@xxxxxxxx>
- Date: Thu, 13 Apr 2006 16:41:01 -0500
On 13 Apr 2006 13:41:34 -0700, "SLC" <dotnetchic@xxxxxxxxx> wrote:
if I have a 2D array of data as in:
int **foo = new int *[first_dimension];
for (i=0; i<first_dimension; i++)
{
foo[i] = new int [second_dimension];
}
will a single call to delete free my memory?
delete [] foo;
No. The compiler has no way of knowing what each foo[i] points to, much
less how (and if) it should be deleted.
or do I need to delete each dimension?
for (i=0; i<first_dimension; i++)
{
delete [] foo[i];
}
delete [] foo;
The second one is what you need. BTW, foo is not a 2D array but a sort of
simulation consisting of an array of pointers to arrays. If
second_dimension is known at compile-time, you could use a real (dynamic)
2D array:
int (*foo)[second_dimension] = new int[first_dimension][second_dimension];
Now this one you would delete with:
delete [] foo;
The difference is that my example creates a 2D array whose data is
contiguous. Your individual row arrays might be spread all over memory.
There is an advanced trick whereby you can get contiguous data even when
the first and second dimensions aren't known until runtime. It involves
allocating a single chunk of memory to contain the row pointers, which
point to the rows within that same chunk of memory, so everything resides
in the same block. You have to take some pains to get the alignment right
for the rows, which follow the row pointer array.
--
Doug Harrison
Visual C++ MVP
.
- Follow-Ups:
- Re: delete for 2D arrays
- From: SLC
- Re: delete for 2D arrays
- References:
- delete for 2D arrays
- From: SLC
- delete for 2D arrays
- Prev by Date: Re: delete for 2D arrays
- Next by Date: CTreeCtrl: checkboxes and spacebar
- Previous by thread: Re: delete for 2D arrays
- Next by thread: Re: delete for 2D arrays
- Index(es):
Relevant Pages
|