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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically allocating memory for array of pointers.

Status
Not open for further replies.

borgrulze

Programmer
Apr 4, 2002
11
0
0
IN
Can anyone inform me as to how to dynamically allocate memory for a pointer to an array of objects using new.

The size of the array of objects is only known at run time.
 
assuming your object is called SomeObject:

// declare a pointer to SomeObject
SomeObject *pSomeObject;

// Find out the number of objects required
DWORD NumberOfObjects = ....;

// Allocate memory for the required number of pointers
pSomeObject = (SomeObject *)( malloc ( NumberOfObjects * sizeof ( SomeObject *)));

// create the objects
DWORD i1;
for ( i1 = 0; i1 < NumberOfObjects; i1++ )
{ pSomeObject + i1 = new SomeObject ( .... ); }

// do something with someobject[5]

(*(pSomeObject + 5)).MemberOfSomeObject ( );

// destruct the objects

for ( i1 = 0; i1 < NumberOfObjects; i1++ )
{ delete ( pSomeObject + i1 ); }

// free the memory
free ( pSomeObject );

 
to use new and delete exclusively (not malloc/free):

// declare a pointer to SomeObject
SomeObject *pSomeObject;

// Find out the number of objects required
DWORD NumberOfObjects = ....;

// Allocate memory for the required number of pointers
pSomeObject = new SomeObject *[NumberOfObjects];

// create the objects

DWORD i1;
for ( i1 = 0; i1 < NumberOfObjects; i1++ )
pSomeObject[i1] = new SomeObject;

pSomeObject[5]->method();

for ( i1 = 0; i1 < NumberOfObjects; i1++ )
delete pSomeObject[i1];

delete [] pSomeObject;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top