-2
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

  • You don't want to use dynamic arrays (e.g., `std::vector`), and you don't have valid C++ code in the snippet anyway, and you have an unknown number of elements. You can have a very large array, say `int arr[1000000];` and use the portion that you need, and if the need exceeds the maximum available size you can throw an exception. – Eljay Apr 18 '21 at 19:15
  • 1
    Sorry, but C++ does not work this way. In C++ the size of all arrays must be ***known at compile-time***. – Sam Varshavchik Apr 18 '21 at 19:16
  • Does this answer your question? [Static array vs. dynamic array in C++](https://stackoverflow.com/questions/2672085/static-array-vs-dynamic-array-in-c) – Enlico Apr 18 '21 at 19:19

1 Answers1

1

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.

Enlico
  • 23,259
  • 6
  • 48
  • 102