Hi all, This question is in C++. I am trying to dynamically allocate an array of pointers to objects. I know I can use a vector container but the point of the exercise is not to...
Here is the code:
void HealthClub::AddHealthClubDevice ( char* HealthClubDeviceName )
{ //We added NumberOfDevices as an attribute, so we won't have to use sizeof all the time
if (NumberOfDevices==0) // This is for the first device we want to add
{
HealthClubDevices = new Device*[1];
HealthClubDevices[0]= new Device(HealthClubDeviceName);
NumberOfDevices++;
}
else // Here we did realloc manually...
{
Device** tempHealthClubDevices;
tempHealthClubDevices = new Device*[++NumberOfDevices]; //this is where we see the first sign of a problem, The tempHealthClubDevices is not allocated properly
for (int i=0 ; i<(NumberOfDevices-1) ; i++)
tempHealthClubDevices[i]=HealthClubDevices[i];
delete[] HealthClubDevices;
HealthClubDevices = tempHealthClubDevices;
HealthClubDevices[NumberOfDevices-1]= new Device(HealthClubDeviceName);
}
}
The Device** objects are not allocated properly, they never grow in size, they are always one element. Does anyone know why? Thanks!