Re: deleting multidimensional arrays

R

Rene Eng

Hi DeeVee

DeeVee said:
I cant figure out how to delete a multi-dimensional array.

For example

int *enum_1 = new int[120][24];
delete [][]enum; does not work.


Also, what are the advantages of declaring arrays like this. Why not just use
int enum[123][24];

The first is an two-dimensional array of pointers to integer values, the
second
is just a two-dimensional array of integer values.
To delete the array, the syntax is
delete [] enum_1;

But: The first array can hold pointers to integer values, and if those
pointers are
created within the program, you need to delete them separately.

Example:
enum_1[ 12][ 5] = new int;
creates such a pointer and

delete emum_1[ 12][ 5]

would delete it again.
If not all of the pointers are used, you should initialise the array after
it was
created, so you can decide which array elements hold pointers you need to
delete.

Example:
int *enum_1 = new int[120][24];
memset( enum_1, '\0', 120 * 24);
....

for (int i = 0; i < 120; i++) {
for (int j = 0; j < 24; j++) {
if (enum_1[ i][ j] != NULL) {
delete enum_1[ i][ j];
}
}
}
delete [] enum_1;


Finally: Such an array may not make much sense with integer values, but
imagine
the array holds structures or objects. Then it makes a big difference if you
hold
only the pointers and create only the structures/objects you really need, or
if you
always create all 120 * 24 = 2880 objects.


hth
René


=======================================
C++ sources, cross-platform (UNIX and WinTel) and
covering several topics: http://gemini.futurezone.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top