此問題使用C++語言編寫。 我想動態分配一個指向對象的指針數組。 我知道我可以使用一個vector容器,但演習的一點是不要......將指針數組動態分配到對象
下面是代碼:
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);
}
}
設備**對象不正確分配,他們永遠也長不大在規模上,他們總是一個元素。 有誰知道爲什麼? 謝謝!
這個問題每次都會發生嗎?新操作員可能無法分配足夠的內存嗎? – computergeek6 2009-11-22 18:33:18
每當它發生這種情況絕對不是內存問題。 – wazuba 2009-11-22 18:41:49
我沒有看到您發佈的代碼有任何問題。儘管您的評論中提到「將NumberOfDevices添加爲屬性,所以我們不必一直使用sizeof」這令人不安。 sizeof運算符不會給你分配的設備數量。 – 2009-11-22 18:49:51