Manually resize array in C++

4026 views c++
6

I am sorry if this has already been covered before. I know how to do this is C and Java but not C++. Without using a pre-existing class which includes the use of Vector, how would you increase the size of an array given the code below?

The array expansion and assignment to the array takes place in push() noted with the all caps comment.

EDIT: As I have mentioned in comments below this is a question regarding manually reallocating arrays rather than using std::vector or "Dynamic Arrays."

Line.h

#include <iostream>
#include "Point.h"

using namespace std;

class Line {
    public:
        Line();
        virtual ~Line();

        // TAKE IN NEW POINT, INCREASE THE ARRAY SIZE AND ADD NEW POINT TO THE END OF THE ARRAY
        void push(const Point& p);

    private:
        unsigned int index;  // size of "points" array
        Point* points;

};

Main.cpp

#include <iostream>
#include "Point.h"
#include "Line.h"

using namespace std;

int main() {

    int x, y;
    int size;           // Some user defined size for the array
    Line line;

    Point a[size];      // Some points that are already filled

    // Push the data in a[] to the variable "line"
    for(int i = 0; i < size; i++){
        // Increase array size of Point* points in variable line and add a[i] to the end of the array
        line.push(points[i]);
    }

    return 0;
}

answered question

When you have a "dynamic array" of any kind in C++, the solution is always to use std::vector.

I am aware of that. The purpose of this excessive is to manually reallocate memory similar to how std::vector would do it. I am aware this is extremely inefficient but again it is for the exercise of learning.

If you know how to do this in C then you know how to do this in C++. Also see stackoverflow.com/q/3482941/390913

1 Answer

7

You basically have no way but to allocate a new array, copy existing values inside and delete [] the old one. That's why vector is doing the reallocation by a multiplicative factor (say each reallocation doubles the size). This is one of the reasons you want to use the standard library structures instead of reimplementing.

posted this

Have an answer?

JD

Please login first before posting an answer.