Mark
Mark

Reputation: 283

Dynamic resizing of an array in C++

I have a class with items pointing to an Airport object. The size of the dynamic array starts off at 10. When total is greater than the size of the array and I have read in data to fill up the array, I need to double the size of the array, copy the elements from the old array into the newly sized array and then delete the old array. The array will continue to read in data, then resize, and continue this until all the data from the file is read into the items array.

There are no errors that occur, but the problem is when I run the program, it crashes. I think my doubleSize function to resize the array might be the cause of this. Is there a way to fix this issue?

class AirportList
{
private:
   Airport* items;
   int total;
   int maxElements;
   int oldAmount;
public:
     AirportList()
     {
        oldAmount = 10;
        maxElements = 10;
        items = new Aiport[maxElements];
        // a file was opened to read in data before this, 
        // total equals the total amount of lines in the file
        string cppstr;
     for (int counter = 0; counter < total; counter++)
     {
        getline(infile, cppstr);
        items[counter] = Airport(cppstr);   // the Airport constructor                       
                                            // parses each line to read in   
                                           //  the data and sets each Airport
                                           //  object into the items array
        if (total > maxElements && counter == maxElements)
            doubleSize(items, maxElements, oldAmount);
     }
        infile.close();
     }

     void doubleSize(Airport*& orig, int maxElements, int oldAmount)
     {
        maxElements = maxElements * 2;
        Aiport* resized = new Aiport[maxElements];
        for (int i = 0; i < oldAmount; i++)
            resized[i] = orig[i];
        delete [] orig;
        orig = resized;
        oldAmount = maxElements;
     }

};

Upvotes: 0

Views: 1433

Answers (2)

hacoo
hacoo

Reputation: 121

I suspect you have an error with the copy constructor for the Airport class. You need to define a copy constructor for Airport (which does a deep copy of its data) and overload the assignment operator to use the new copy constructor. Otherwise, when you do resized[i] = orig[i];, you will do a shallow copy which ends up still pointing to data in the original (now deleted) Airport object.

Take a look here: http://www.cplusplus.com/articles/y8hv0pDG/

Upvotes: 0

xaxxon
xaxxon

Reputation: 19761

You don't double the size until after you've made an assignment to the array where counter == maxelements, but items[maxelements] isn't valid -- only maxelements - 1.

If you move doublesize up above the assignment, things should work better.

Also, there's no reason to check if total > maxElements. It's simply not necessary.

Upvotes: 3

Related Questions