What is the proper way of deleting a new struct array that contains new struct array?
typedef struct CALF_STRUCTURE
{
char* Name;
bool IsBullCalf;
} CALF;
typedef struct COW_STRUCTURE
{
CALF* Calves;
} COW;
int main( void )
{
COW* Cows;
Cows = new COW[ 3 ]; // There are 3 cows.
Cows[ 0 ].Calves = new CALF[ 2 ]; // The 1st cow has 2 calves.
Cows[ 1 ].Calves = new CALF[ 1 ]; // The 2nd cow has only 1 calf.
Cows[ 2 ].Calves = new CALF[ 25 ]; // The 3rd cow has 25 calves. Holy cow!
Cows[ 2 ].Calves[ 0 ].Name = "Bob"; // The 3rd cow's 1st calf name is Bob.
// Do more stuff...
Now, its time do clean-up! But…what is the proper way of deleting the cows and calves array or any type of struct array?
Should I delete all of the cows’s calves array in a for-loop first? Like this:
// First, delete all calf struct array (cows[x].calves)
for( ::UINT CowIndex = 0; CowIndex != 3; CowIndex ++ )
delete [ ] Cows[ CowIndex ].Calves;
// Lastly, delete the cow struct array (cows)
delete [ ] Cows;
return 0;
};
Or should I just simply delete the cows array and hope that it will also delete all calves array? Like this:
// Done, lets clean-up
delete [ ] Cows;
return 0;
};
Or?
Neither. To do this in C++:
and
and, in
main:By magic, you no longer need to delete anything.