Search code examples
c++carraysmallocdynamic-allocation

Increase array size at runtime in c++ without vector, pointer


I have declared a array of int in c++ with some size. say, int a[6]

at runtime if my array size exceeds 6, then i need to increase it.

i am not going to use pointer, vector and the size will not be given by the user.


Solution

  • You can not change the size of your array at run time. An alternative is to create a new array which is larger than the existing one. Copy the elements of the existing array to the new array and delete the existing array. And Change the member variables, ptr and size.

    Something like this:

    int* newArray = new int[sizeOfArray];
    std::copy(oldArray, oldArray + std::min(sizeofOldArray, sizeOfArray), newArray);
    delete[] oldArray;
    oldArray = newArray;
    

    The best is to use the std::vector