Rob
Rob

Reputation: 11

How to "resize" a dynamic array of objects in c++

Lets say I have a class player, which has the member variables num_houses and a pointer temp1 of type house

class player{
private:
    int num_houses;
    house* temp1;
public:
    player(){
    num_houses = 0;
    temp1 = new house[num_houses];
}

My question lies with my code when I try to resize or basically add/remove an element of type house to my array of houses. In my code I happen to be getting a segmentation fault. I'm confused and I am a student so any advice or criticism will help me dearly!

void player::add_house(house tkn){
    house* temp = new house[num_houses];
    for(int i = 0; i < num_houses; i++){
        temp[i] = temp1[i];
    } 
    num_houses++;
    if(temp1 != NULL){
        delete [] temp1;
    }
    temp1 = new house[num_houses];
    for(int i = 0; i < num_houses-1; i++){
        temp1[i] = temp[i];
    }
    temp1[num_houses-1] = tkn;
    delete [] temp;
}

Upvotes: 1

Views: 3287

Answers (2)

user4624958
user4624958

Reputation:

For increasing array size rewrite your algo to perform these steps:

  1. Allocate new temp array with size of current+1.
  2. Copy everything from current array to temp array.
  3. Increment houses amount.
  4. delete current array.
  5. Save the pointer to temp array to the current array pointer.
  6. Add new house to the end of current array.

Of course you can reorder this list if you understand how (4 is always after 1, 6 is always after 1, 5 is always after 4 etc.).

P.S. you don't have to check if pointer is not null before deleting it - deleting nullptr won't fail.

UPD: added code

void player::add_house(house tkn {
    house* temp = new house[num_houses + 1];
    for(int i = 0; i < num_houses; i++) {
        temp[i] = temp1[i];
    }
    num_houses++;
    delete [] temp1;
    temp1 = temp;
    temp1[num_houses-1] = tkn;
}

Upvotes: 1

R Sahu
R Sahu

Reputation: 206597

temp1 = new house[num_houses];

is a problem when num_houses is 0.

Change the default constructor to:

player() : num_houses(0), temp1(nullptr) {}

You can simplify the member function add_house so it requires one less pair of new/delete.

void player::add_house(house tkn){

    num_houses++;
    house* temp = new house[num_houses];
    for(int i = 0; i < num_houses-1; i++){
        temp[i] = temp1[i];
    } 

    temp[num_houses-1] = tkn;

    if(temp1 != nullptr){
        delete [] temp1;
    }

    temp1 = temp;
}

Upvotes: 1

Related Questions