Destructor for a 2d Array

Hello there!

Have written a program for the first time using a matrix(2d array)
Kinda stuck on writing the destructor for it,gettin memory leaks.

Constructor:
1
2
3
4
5
6
	this->Towns=new string[10];
	this->graph=new int*[10];
	for(int i=0;i<nroftowns;i++)
	{
		this->graph[i]=new int[10];
	}


My desctuctor so far:

1
2
3
4
5
6
	delete [] Towns;
	for(int i=0;i<nroftowns;i++)
	{
		delete this->graph[i];
	}
	delete []graph;


have tried to write it like this:
1
2
3
4
5
6
7
8
9
	delete [] Towns;
	for(int i=0;i<nroftowns;i++)
	{
		for(int j=0;j<nroftowns;i++)
		{
			delete this->graph[i][j];
		}
	}
	delete []graph;


but my compilator complains about "this->"graph[i][j];

Any help is greatly appreciated:)
Depends on how you allocated it. In your case, you would just reverse it:

1
2
3
4
5
6
delete [] Towns;
for(int i=0;i<nroftowns;i++)
{
	delete [] this->graph[i]; //this part was allocated with new[], so use delete[]
}
delete []graph;
Makes sence..still gettin memory leaks tho,and the only place i alocate new memory is in the constructor..
Are you sure you aren't messing with the pointers anywhere? If they change, that could be a leak.
Yeah,i have a default constructor and a custom one,which are pretty much the same.
No idea where the memory leak occurs.
No idea where the memory leak occurs.


Which is exactly why you should objectify this thing, and not work with memory management directly.

I just did something like this recently:

http://www.cplusplus.com/forum/general/42747/#msg231082

Using that class would make this much easier for you.
Found where the memory leak occurs,problem solved;)
Topic archived. No new replies allowed.