此问题使用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