Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Array sizing

Status
Not open for further replies.

mattKnight

Programmer
May 10, 2002
6,239
GB
There must be a "standard" way of doing this...

Suppose I have a class, which I allocate on the heap

Code:
MyClass * pMyClassInst[5];

pMyClassInst[0] = new MyClass

The above limits me to having 5 instances on MyClass.

How can I size or resize that array pMyClassInst as runtime?

What do I need to read up? As you can tell I a little new to C++!!



Take Care

Matt
If at first you don't succeed, skydiving is not for you.
 
Sizing is easy:
Don't say it's 5, just say it's X. And set X to whatever suits your needs at runtime.

Resizing involves just a bit more work:
For example; you could use malloc and realloc to store pointers to the classes in a block of memory that's resizable.


Greetings,
Rick
 
Try using vectors or lists

Code:
#include <vector>
typedef std::vector<MyClass*> MyClassVec;

MyClassVec pClassInst;

// To add a new one
pClassInst.push_back(new MyClass);

It is the same for lists except you cannot address them as pClassInst[x].
 
Just to add to the confusion, I'll contribute the modern standard dynamic memory allocation method (using operators 'new' and 'delete').

//declare variables
int n = 5;
MyClass *pMyClassInst;

//size it at run-time... creates an array of 'n' size
pMyClassInst = new MyClass[n];


As you may know, when you use dynamic memory allocation in your program, you need to manually reclaim the memory using operator delete when you are through with the object(s). To delete an array, use delete with '[]'.

//delete the array you created
delete[] pMyClassInst;

Resizing can be acheived by creating a new array dynamically, then copying the old information before deleting the original array, but as XWB suggests, you may also use STL templates which will do all of this for you behind the scenes.

Hope that helps! :)
 
Note Bolderbum's suggestion will only work on C99 compilers.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top