I am trying to understand the difference between static and dynamic arrays in C++ and I can not think of a case where a static array would not do the trick.
I am considering a static array that would be declared this way:
int N=10;
int arr[N];`
I read here that the main difference between static and dynamic array is that a static array is allocated during compilation so N needs to be know at compilation.
However, this explains that arrays declared this way can also be Variable-length arrays:
Variable-length arrays were added in C99 - they behave mostly like fixed-length arrays, except that their size is established at run time; N does not have to be a compile-time constant expression:`
and indeed, the following c++ code is working, even though n
is only known at runtime :
int n =-1;
std::cin>>n;
int arr[n];
//Let the user fill the array
for(int i=0; i<n;i++){
std::cin>>arr[i];
}
//Display array
for(int i=0; i<n;i++){
std::cout<<i<<" "<<arr[i]<<std::endl;
}
So I would like an example of code were a static arrays defined like this would not work and the use of dynamic array would be required ?