this is a part of an assignment for my programming class. the teacher wanted us to create a couple of functions, one of which would add elements to an existing dynamic array of structures, and this is what I have troubles with.
here's my understanding of how the function should work, based on different posts I found online:
create a new array, bigger than the one already existing
copy the content of the old array to the new array
add the new element to the new array
destroy the old array
however, something is wrong, and the program crashes - I think the problem lies in the way I'm trying to do points 3 and 4. Can someone take a look? I'd really appreciate any kind of help.
edit: forgot to mention, the teacher wants the functions set to void, they are supposed to not return anything.
Here is the code:
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- hard work done for you!size_trather thanintfor array sizes. It's much more compatible with other bits of C++.