Sign in to follow this  
TigerSam

Deleting 2D array of pointers

Recommended Posts

TigerSam    122
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[i][j] = new * SomeType(); } } Any help appreciated. Cheers

Share this post


Link to post
Share on other sites
Brother Bob    10344
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].

Share this post


Link to post
Share on other sites
davj88    130
I am not really sure, maybe

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

won't work?

I'm a beginner, I'd like to learn too :P

Share this post


Link to post
Share on other sites
Morrandir    304
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.

Share this post


Link to post
Share on other sites
SyncOrSwim    150
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[i][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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this