Question about freeing multidimensional arrays of pointers

C

countofquad

What I need is a 2D array of pointers to instances of class foo.
Here is a simplified example of what I do to allocate the memory.

class foo
{

public:

int x;
int y;

};


// example 2d array

int x_max = 10;
int y_max = 10;

foo ***map;

map = new (foo **) [x_max];

for(int x = 0; x < x_max; x++) {
map[x] = new (foo *) [y_max];
}

for(int y = 0; y < y_max; y++) {
for(int x = 0; x < x_max; x++) {
map[x][y] = new foo();
}
}

But I have no idea how to free the memory once I'm done using map.

I tried using:

for(int x = 0; x < x_max; x++) {
delete [] map[x];
}

delete map;

But this doesn't seem to free it up. I've been wringing my hair for a
couple of hours trying to figure this out, so many thanks to those who
can help me with this.

Shaun
 
X

xeno

On Fri, 4 Mar 2005, countofquad wrote:

/*
What I need is a 2D array of pointers to instances of class foo.
....
*/

#include <iostream>

class foo
{

int _x;
int _y;
public:

foo() : _x(0), _y(0) {}
void set_xy(int x, int y) { _x = x; _y = y; }
~foo() { std::cout << "Foo dtor<" << _x << "," << _y << ">" << std::endl; }


};

const int MAX = 10;

int main() {


foo *f[MAX][MAX];

for(int i = 0; i < MAX; i++)
for(int j = 0; j < MAX; j++)
f[j] = new foo;

for(int i = 0; i < MAX; i++)
for(int j = 0; j < MAX; j++)
f[j]->set_xy(i+1,j+1);


for(int i = 0; i < MAX; i++)
for(int j = 0; j < MAX; j++)
delete f[j];

}
 
M

marbac

countofquad said:
// example 2d array

int x_max = 10;
int y_max = 10;

foo ***map;

map = new (foo **) [x_max];

for(int x = 0; x < x_max; x++) {
map[x] = new (foo *) [y_max];
}

I would do it this way:

int rows=5;
int cols=5;

foo a_test_foo;

foo** mat = new foo*[rows];
for (int i=0;i<rows;i++)
mat = new foo[cols];

foo[1][4]=a_test_foo;





results in

mat -> mat[0] -> [?][?][?][?][?] .....
mat[1] -> [?][?][?][?][a_test_foo] .....
mat[2] -> [?][?][?][?][?] .....
 
C

countofquad

Here's the thing though.

I need the array to be dynamically allocated, and some of the pointers
within the matrix, eg map[j], may be NULL sometimes, they will be
constructed in the future.

I also want to be able to pass pointers to various instances of foo
within the matrix like:

void alterFoo(foo *f)
{
...
}

I don't think I can do this, if I construct a map with

foo **map = new foo *[some_value];

I think I need to use:

foo ***map;


I tried to delete the array, by deleting every element within the
matrix:

for(int x = 0; x < x_max; x++) {
for(int y = 0; y < y_max; y++) {
delete map[x][y];
}
}

But it still leaks memory.

Thanks,
Shaun
 

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

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top