【发布时间】:2009-11-22 18:21:26
【问题描述】:
这个问题是用 C++ 编写的。 我正在尝试动态分配指向对象的指针数组。 我知道我可以使用矢量容器,但练习的重点不是......
代码如下:
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);
}
}
Device** 对象没有正确分配,它们的大小永远不会增长,它们始终是一个元素。 有谁知道为什么? 谢谢!
【问题讨论】:
-
是不是每次都会出现这个问题?有没有可能是 new 运算符无法分配足够的内存?
-
每次都会出现这种情况,绝对不是内存问题。
-
我没有发现您发布的代码有任何问题。尽管您的评论说“添加 NumberOfDevices 作为属性,所以我们不必一直使用 sizeof”令人不安。 sizeof 运算符不会给您分配的设备数量。
标签: c++ arrays dynamic pointers