这个问题在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 **对象没有正确分配,它们的大小永远不会增长,它们总是一个元素。 有谁知道为什么? 谢谢!
答案 0 :(得分:4)
无法重现您的问题。具体来说,这里是我编译并成功运行的所有骨架代码 - 您的方法加上最小的脚手架,使其成为一个完整的程序:
#include <iostream>
struct Device {
char* name;
Device(char* n) {name = n;}
};
struct HealthClub {
int NumberOfDevices;
Device** HealthClubDevices;
HealthClub() { NumberOfDevices = 0;}
void AddHealthClubDevice(char *);
};
std::ostream& operator<<(std::ostream& o, const HealthClub& h) {
o << h.NumberOfDevices << " devices:" << std::endl;
for(int i=0; i<h.NumberOfDevices; ++i) {
o << " " << h.HealthClubDevices[i]->name << std::endl;
}
o << "That's all!\n" << std::endl;
return o;
}
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);
}
}
int main() {
HealthClub h;
std::cout << h;
h.AddHealthClubDevice("first");
std::cout << h;
h.AddHealthClubDevice("second");
std::cout << h;
h.AddHealthClubDevice("third");
std::cout << h;
return 0;
}
编译很好,即使是--pedantic,当运行时发出:
$ ./a.out
0 devices:
That's all!
1 devices:
first
That's all!
2 devices:
first
second
That's all!
3 devices:
first
second
third
That's all!
根据需要。所以,你的问题的原因必须在别的地方。鉴于您的真实程序失败(您没有告诉我们具体如何)和这个成功的最小程序,您可以“通过二分插值”来构建最小的失败案例 - 如果仍然没有告诉您问题所在发布最小失败案例和小于它的一个epsilon仍然成功作为SO问题肯定能得到你需要的帮助(一定要指定编译器,操作系统等)。