May 1, 2002 #1 borgrulze Programmer Joined Apr 4, 2002 Messages 11 Location 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.
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.
May 1, 2002 #2 MKuiper Programmer Joined Jan 29, 2002 Messages 364 Location NL 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 ); Upvote 0 Downvote
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 );
May 1, 2002 #3 jtm111 Programmer Joined Jun 27, 2001 Messages 103 Location US 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; Upvote 0 Downvote
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;