Page 1 of 1

C++ Dynamic Memory Allocation

Posted: Sun Jan 09, 2011 5:45 pm
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.

Posted: Sun Jan 09, 2011 6:28 pm
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;

Posted: Sun Jan 09, 2011 6:45 pm
by Alpha Omega
Thanks so much it works great now :)

Posted: Sun Jan 09, 2011 11:00 pm
by Lonesome Ducky
The first method you posted though is how you would delete an array of pointers, just so you know :)