Dynamic Memory Allocation in C++

Ever wondered how you can create a resizable array in C/C++? I will not be discussing the C stuff here since I'm not  at all that good in C. So let's try to take a look on how to make dynamic memory allocation in C++.

1
2
3
4
5
6
7
8
9
10
11
class MyClass
{
private:
int *myvararray;

public:
MyClass(int n)
{
myvararray = new intNo;
}
}


Here, you create a pointer to an int. Then using the new operator(C++ only) create an array
with n size. That's how easy it is actually. But how about when you need to make dynamic
memory allocation for pointer types? Here is a snippet just on how to do that. This is taken
from the Animation class that I created for my game.

Make a pointer, to the pointer

1
BITMAP** animationFrames; //this is a member


then for example, you in your constructor you can do it like this.

1
2
3
4
5
6
7
    animationFrames = new BITMAP*[maxFrames];

for (int i = 0; i < maxFrames; i++)
{
animationFramesIdea = create_sub_bitmap(bitmap, currentX, 0, frameWidth, frameHeight);
currentX += frameWidth;
}

 
Simple isn't it? Hope that helps! ;)

Published 02-27-2007 3:16 AM by lamia
Filed under: