C++ Dynamic Memory Allocation

Post your questions, suggestions and experiences regarding game design, integration of external libraries here. For irrEdit, irrXML and irrKlang, see the
ambiera forums
Post Reply
Alpha Omega
Posts: 288
Joined: Wed Oct 29, 2008 12:07 pm

C++ Dynamic Memory Allocation

Post by Alpha Omega »

So I am new to using dynamic memory allocation commands in C++;

I have an array that holds a certain ClassType. I allocate memory with new for 10 positions of ClassType. At the end of the program I want to clean up the allocated memory so I delete all the ClassTypes in the array because I called them with new also. I want to do this but with a large class type.

Code: Select all


for(int i=0;i<length;i--)
    {
        delete arr+i;
    }
    delete [] arr;

But arr + i will not effectively move down the array will it because int is 2 bytes and my ClassTypes are bigger than 2 bytes.

Will this work ?

Code: Select all


for(int i=0;i<length;i--)
    {
        delete *arr[i];
    }
    delete [] arr;

Also the array is part of a Class that acts like a stack and has private members of the array and the length which is also allocated with new.
Bate
Posts: 364
Joined: Sun Nov 01, 2009 11:39 pm
Location: Germany

Post by Bate »

You don't have to delete each item individually. All you need to do is this:

Code: Select all

class C
{
  // stuff
};


C* ptr = new C[10];
delete [] ptr;
Never take advice from someone who likes to give advice, so take my advice and don't take it.
Alpha Omega
Posts: 288
Joined: Wed Oct 29, 2008 12:07 pm

Post by Alpha Omega »

Thanks so much it works great now :)
Lonesome Ducky
Competition winner
Posts: 1123
Joined: Sun Jun 10, 2007 11:14 pm

Post by Lonesome Ducky »

The first method you posted though is how you would delete an array of pointers, just so you know :)
Post Reply