Search code examples
c++dynamic-arrays

How to take input to an array with unknown number of elements? ( I don't wanna use std::vector )


int n = 5;
int arr[n];
for (int i =0; i<n; i++){
    cout << "enter number" <<endl;
    cin >> arr[i];
}

but what if the number of inputs is unknown? how can I take the unknown number of inputs in an array


Solution

  • Once you do

    int arr[n];
    

    the size of the array is decided, once and for all. There's no way you can change it.

    On the other hand, you can dynamically allocate memory to which a pointer points to.

    int * arr;
    arr = new int[n];
    // now you can use this arr just like the other one
    

    If you need, later, to change the size of the memory to which arr points, you can deallocate and reallocate as needed.

    delete [] arr;
    arr = new int[m];
    // probably there's a more idiomatic way of doing this, but this is really too
    // much C for me to care about this details...
    

    Obviously you need to think about how you can take care of copying the values to another temporary array to avoid loosing them during the deallocation-reallocation process.

    All this madness, however, is not necessary. std::vector takes care of all of that for you. You don't want to use it? Fine, but you're not writing C++ then. Full stop.