[英]Dynamic object creation of an array of pointers
I try to create objects dynamically. 我尝试动态创建对象。 Each object is a pointer in an array of pointers.
每个对象都是指针数组中的一个指针。 The compiler gives me
编译器给我
error C4700: uninitialized local variable 'villages' used.
And I can not figure out how to fix it. 而且我不知道如何解决它。 I would be very grateful to all the helpers.
我将非常感谢所有帮助者。
int villageAmount;
cout << "Defining villages:\n\nEnter how many villages do you want: ";
cin >> villageAmount;
Village **villages;
for (int i = 0; i < villageAmount; i++)
{
cout << "\nDefining village's details #" << i + 1 << ":\n";
villages[i] = new (nothrow) Village;
}
Village **villages;
you declared villages
without initializing, so it contains garabage valaue. 您声明
villages
未进行初始化,因此其中包含垃圾垃圾。
for (int i = 0; i < villageAmount; i++)
{
cout << "\nDefining village's details #" << i + 1 << ":\n";
villages[i] = new (nothrow) Village;
}
right below, you access into it and writes. 在下面,您可以对其进行访问并进行编写。 That's no no.
那不行
If you want to store pointer of village (ie type of Village*
) dynamically, you also need to allocate them. 如果要动态存储村庄的指针(即
Village*
类型),则还需要分配它们。
Village **villages = new Village*[villageAmount];
Or if amount is fixed, 或者如果金额固定,
Village *villages[10] = { nullptr, }; // 10, 12344, or whatever
villages memory is never allocated, you should use a vector or any sort of container (an array look fine here). 村庄的内存从未分配过,您应该使用向量或任何种类的容器(在此看起来不错的数组)。 If you really want to allow the memory manually you could do something like :
如果您真的想手动允许内存,可以执行以下操作:
Village **villages = new Village*[villageAmount];
Don't forget to free EVERY new, (If you only free villages, all the Village* that he contain will remain allocated. 别忘了释放每个新的(如果您仅释放村庄,那么他包含的所有村庄*将保持分配状态。
Edit : someone else answered so I guess my answere is usless 编辑:有人回答,所以我想我的回答是无用的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.