Deleting 2D array of pointers

Started by
5 comments, last by SyncOrSwim 15 years, 11 months ago
Hi All As the title says how would i go about deleting a 2d array of pointers if i declared the arrray: for(int i=0; i<noCols; i++) { for(int j=0; j<noCols; j++) { SomeType array[j] = new * SomeType(); } } Any help appreciated. Cheers
Advertisement
You have to delete exactly what you allocate. So if you allocate storage for array[m][n] for all m and n, then you have to delete array[m][n] for all m and n also. So, two loops, and delete array[m][n].
I am not really sure, maybe

for(int i=0; i<noCols; i++)
{
for(int j=0; j<noCols; j++)
{
delete array[j];
}
}

won't work?

I'm a beginner, I'd like to learn too :P
I dont know why i didnt think of using that. I was too busy thinking i should be using delete[]. Cheers Guys
Hi!

First of all, that isn't really the declaration of your array. It's the piece of code that fills your array with values.

Second, I don't know what you're trying to achieve with this piece of code, but it looks weird. To be honest, I don't really know what
new * SomeType()
is supposed to return. If you want to allocate a new SomeType object on the heap, you call
 new SomeType() 
, without the asterisk.
Are you trying to delete the array or the things that the array points to?
It's probably just the result of some rushed typing on your part but your code snippet is all kinds of broken!

For the benift of clairty (and to avoid confusing others who might stumble across your question) I presume you meant something like this?

const int noCols = 10;SomeType * array[noCols][noCols];for(int i=0; i<noCols; i++){	for(int j=0; j<noCols; j++)	{		array[j] = new SomeType();	}}


That's assuming of course that we are dealing with a fixed array of pointers to "SomeType" as apposed to a heap allocated array of pointers (In essence what Ezbez is asking?). If this is the case then you already have your solution courtesy of davj88 and Brother Bob.

Ben

This topic is closed to new replies.

Advertisement