delete [] and multidimensional arrays?

If I'm doing something like this:
1
2
3
4
5
6
7
8
void function() {
   int my_int[5][6][7];

   for(int i=0; i<5; i++)
      for(int j=0; j<6; j++)
         for(int k=0; k<7; k++)
            my_int[i][j][k] = 100*i+10*j+k;
}

How do I need to use delete []? Is it simple like this:

1
2
3
4
5
6
7
8
9
10
void function() {
   int my_int[5][6][7];

   for(int i=0; i<5; i++)
      for(int j=0; j<6; j++)
         for(int k=0; k<7; k++)
            my_int[i][j][k] = 100*i+10*j+k;

   delete [] my_int;
}


or do I have to do loops deleting parts of the array before doing delete [] my_int; ?

Any help would be greatly appreciated. Thanks! =)
Last edited on
You don't want to use delete[] as you didn't use new to allocate anything onto the heap. Your whole array is on the stack, and isn't dynamic.
I see, thanks for the info. What if i have some other class with an "obj" object and I want to declare an array of "obj *" pointers to objects like so:

1
2
3
4
5
6
obj * my_objects[5][6][7];

for(int i=0; i<5; i++)
      for(int j=0; j<6; j++)
         for(int k=0; k<7; k++)
            my_objects[i][j][k] = new obj(i,j,k);


Where obj(i,j,k) would be a constructor call for the object. is this too general of an example or can you tell me what I would do with delete in this case?

Thanks again.
Last edited on
You mean somthing like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class obj
{
public:
	obj(){}
	~obj(){}
};

int main()
{
	obj* my_objects[5][6][7];

	for (int a = 0; a < 5; ++a)
		for (int b = 0; b < 6; ++b)
			for (int c = 0; c < 7; ++c)
				my_objects[a][b][c] = new obj();

	// do stuff

	// cleanup:
	for (int a = 0; a < 5; ++a)
		for (int b = 0; b < 6; ++b)
			for (int c = 0; c < 7; ++c)
				delete my_objects[a][b][c];

	return 0;
}
yes, that's exactly the situation I mean. So that's the proper implimentation of delete for that case?

Thanks again so much for the help =)
The only case you need a delete[] operator is in case you new'ed a multidimensional array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int * Data[2][2];
for(int a = 0; a < 2; ++a)
{
    for(int b = 0; b < 2; ++b)
    {
        Data[a][b] = new int; // you use the new operator.
    }
}
for(int a = 0; a < 2; ++a)
{
    for(int b = 0; b < 2; ++b)
    {
        delete Data[a][b]; // so you must use the delete operator.
    }
}



for(int a = 0; a < 2; ++a)
{
    for(int b = 0; b < 2; ++b)
    {
        Data[a][b] = new int[8]; // you use the new[] operator.
    }
}
for(int a = 0; a < 2; ++a)
{
    for(int b = 0; b < 2; ++b)
    {
        delete[] Data[a][b]; // so you must use the delete[] operator.
    }
}
Topic archived. No new replies allowed.