phoiboss phoiboss - 1 year ago 181
C++ Question

C++ adding elements to an array

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:

  1. create a new array, bigger than the one already existing

  2. copy the content of the old array to the new array

  3. add the new element to the new array

  4. 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;


Answer Source
void addplayer(Player * plarr, int size) {

The plarr parameter is passed to this function by value.

This function appears to allocate a new array and copy over the contents correctly, except for one error:

temp[size+1].name = name;
temp[size+1].kind = kind;

The index should be size, here. But the biggest error is that the function concludes with:

    delete[] plarr;     
    plarr = temp; 

Unfortunately, since plarr was passed by value, all this does is set the plarr parameter to this function to the new pointer, and returns.

Which accomplishes absolutely nothing, since the caller to this function still has its original pointer. Which is now destroyed.

You should change this function to return the new pointer, which the caller will need to save, instead of the original pointer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download