【发布时间】:2016-11-13 15:40:07
【问题描述】:
这是我的编程课作业的一部分。老师希望我们创建几个函数,其中一个可以将元素添加到现有的动态结构数组中,这就是我遇到的麻烦。
根据我在网上找到的不同帖子,这是我对函数应该如何工作的理解:
创建一个比现有数组更大的新数组
将旧数组的内容复制到新数组中
将新元素添加到新数组中
销毁旧数组
但是,出了点问题,程序崩溃了 - 我认为问题在于我尝试执行第 3 点和第 4 点的方式。有人可以看看吗?我真的很感激任何帮助。
编辑:忘了说,老师希望函数设置为 void,它们应该不返回任何东西。
代码如下:
const int size = 2;
struct Player {
string name;
string kind;
};
void addplayer(Player * plarr, int size) {
cout << "Adding a new element to the array" << endl << endl;
//creating a new, bigger array:
Player * temp = NULL;
temp = new Player[size+1];
//copying the content of the old array
for (int i=0;i<size;i++) {
temp[i].name = plarr[i].name;
temp[i].kind = plarr[i].kind;
}
//adding the new element:
string name, kind;
cout << "Choose the name for the new player: " << endl;
cin >> name;
cout << "Choose the class for the new player: " << endl;
cin >> kind;
temp[size+1].name = name;
temp[size+1].kind = kind;
//deleting the old array, replacing it with the new one
delete[] plarr;
plarr = temp;
}
【问题讨论】:
-
为什么不使用
std::vector- 辛苦了! -
@EdHeal 老师禁止了,很遗憾
-
@EdHeal:对于动态分配的工作原理,这不会非常有指导意义吧?
-
不是你的问题,但从长远来看,如果你使用
size_t而不是int作为数组大小,事情会更容易。它与 C++ 的其他部分更兼容。 -
还要看看 RAII。在这种情况下,您可以构建一个 Player_array 类来在销毁时自动管理和删除数组。